如何解决此String构造函数JAVA出现问题
我正在尝试使用构造函数
public String(byte[] bytes,Charset charset)
详细说明here。 我正在使用它将字节数组转换为ASCII。这是代码
String msg = new String(raw,"US-ASCII");
不幸的是,这给了我
error: unreported exception UnsupportedEncodingException; must be caught or declared to be thrown
String msg = new String(raw,"US-ASCII");
^
尝试使用其他配置,例如““ String msg = new String(data,0,data.length,” ASCII“);”也不起作用。
这不再是可用的构造函数,还是我做错了什么?
解决方法
byte[] raw = new byte[]{};
String msg = new String(raw,StandardCharsets.US_ASCII);
,
说明
问题在于您可能正在写new String(raw,"nonsensefoobar")
,这显然是毫无意义的。
因此Java迫使您告诉它您打算如何处理这种编码方案不存在的特殊情况。通过 try-catching 或声明 throws :
public void myMethod(){
...
try {
String msg = new String(raw,"US-ASCII");
...
} catch (UnsupportedEncodingException e) {
... // handle the issue
}
...
}
// or
public void myMethod() throws UnsupportedEncodingException {
...
String msg = new String(raw,"US-ASCII");
...
}
这是一个非常普通和常见的例外情况,我建议了解例外情况。
更好的解决方案
您可以使用构造函数的另一种重载,而不是将编码方案指定为字符串,然后再处理异常,该重载采用Java知道它们存在的预定义方案,因此不会因异常而困扰您:
String msg = new String(raw,StandardCharsets.US_ASCII);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。