简体   繁体   English

此字符串构造函数(JAVA)的问题

[英]Problem with this String constructor (JAVA)

I am trying to use the constructor我正在尝试使用构造函数

public String(byte[] bytes,
              Charset charset)

Which is detailed here . 此处详细介绍。 I'm using it to convert an array of bytes to ASCII.我正在使用它将字节数组转换为 ASCII。 Here is the code这是代码

String msg = new String(raw, "US-ASCII");

Unfortunately, this gives me:不幸的是,这给了我:

error: unreported exception UnsupportedEncodingException; must be caught or declared to be thrown
    String msg = new String(raw, "US-ASCII");
                 ^

Trying a different configuration like "String msg = new String(data, 0, data.length, "ASCII");"尝试不同的配置,例如“String msg = new String(data, 0, data.length, "ASCII");" Dosen't work either.也不行。

Is this no longer a usable constructor, or am I doing something wrong?这不再是一个可用的构造函数,还是我做错了什么?

byte[] raw = new byte[]{};
String msg = new String(raw, StandardCharsets.US_ASCII);

Explanation解释

The problem is that you could be writing new String(raw, "nonsensefoobar") which obviously is non-sense.问题是您可能正在编写new String(raw, "nonsensefoobar")这显然是无意义的。

Hence Java forces you to tell it how you want to deal with the exceptional case that this encoding scheme does not exist.因此 Java 迫使你告诉它你想如何处理这种编码方案不存在的例外情况。 Either by try-catching it or by declaring throws :通过尝试捕获它或通过声明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");
    ...
}

That is a super ordinary and common exception-situation, I would suggest to learn about exceptions .这是一个超级普通和常见的异常情况,我建议学习 exceptions


Better solution更好的解决方案

Instead of specifying the encoding scheme as string and then dealing with exceptions, you can use another overload of the constructor which takes in predefined schemes for which Java knows that they exist, so it will not bother you with exceptions:除了将编码方案指定为字符串然后处理异常,您可以使用构造函数的另一个重载,它接受 Java 知道它们存在的预定义方案,因此它不会因异常而困扰您:

String msg = new String(raw, StandardCharsets.US_ASCII);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM