类型不匹配:无法从 StringBuilder 转换为 String

2022-09-01 15:19:20

此方法返回给定 URL 的源。

private static String getUrlSource(String url) {
    try {
        URL localUrl = null;
        localUrl = new URL(url);
        URLConnection conn = localUrl.openConnection();
        BufferedReader reader = new BufferedReader(
            new InputStreamReader(conn.getInputStream()));
        String line = "";
        String html;
        StringBuilder ma = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            ma.append(line);
        }
        return ma;
    } catch (Exception e) {
        Log.e("ERR",e.getMessage());
    }
}

它给了我这个错误:

Type mismatch: cannot convert from StringBuilder to String

还有两种选择:

  1. Change the return type to StringBuilder.但我希望它返回一个字符串。
  2. Change type of ma to String.更改字符串后没有 append() 方法。

答案 1

只需使用

return ma.toString();

而不是

return ma;

ma.toString()返回 StringBuilder 的字符串表示形式。

有关详细信息,请参阅 StringBuilder#toString()

正如Valeri Atamaniouk在评论中建议的那样,您还应该在块中返回一些内容,否则您将收到编译器错误,因此编辑catchmissing return statement

} catch (Exception e) {
    Log.e("ERR",e.getMessage());
}

} catch (Exception e) {
    Log.e("ERR",e.getMessage());
    return null; //or maybe return another string
}

这将是一个好主意。


编辑

正如Esailija所建议的,我们在这个代码中有三个反模式。

} catch (Exception e) {           //You should catch the specific exception
    Log.e("ERR",e.getMessage());  //Don't log the exception, throw it and let the caller handle it
    return null;                  //Don't return null if it is unnecessary
}

所以我认为最好做这样的事情:

private static String getUrlSource(String url) throws MalformedURLException, IOException {
    URL localUrl = null;
    localUrl = new URL(url);
    URLConnection conn = localUrl.openConnection();
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(conn.getInputStream()));
    String line = "";
    String html;
    StringBuilder ma = new StringBuilder();
    while ((line = reader.readLine()) != null) {
        ma.append(line);
    }
    return ma.toString();
}

然后,当您调用它时:

try {
    String urlSource = getUrlSource("http://www.google.com");
    //process your url source
} catch (MalformedURLException ex) {
    //your url is wrong, do some stuff here
} catch (IOException ex) {
    //I/O operations were interrupted, do some stuff here
}

查看以下链接以获取有关 Java 反模式的更多详细信息:


答案 2

在将StringBuilder转换为String时,我遇到了同样的问题,我使用了上述观点,但这并没有给出正确的解决方案。使用上面的代码输出是这样的

    String out=ma.toString();
// out=[Ljava.lang.String;@41e633e0

之后,我找到了正确的解决方案。思考是创建一个新的字符串即时插入的字符串生成器,就像这样。

String out=new String(ma);

推荐