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

时间:2013-04-22 20:08:36

标签: java android

此方法返回给定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. 更改String后没有append()方法。

2 个答案:

答案 0 :(得分:53)

只需使用

return ma.toString();

而不是

return ma;

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

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

正如Valeri Atamaniouk在评论中建议的那样,你也应该在catch块中返回一些东西,否则你会得到missing 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反模式的更多详细信息:

答案 1 :(得分:0)

尝试

返回ma.toString(); 因为您不能直接将stringbuilder变量存储到字符串变量中。