types不匹配:不能从StringBuilder转换为String

此方法返回给定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 

还有两个select:

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

Solutions Collecting From Web of "types不匹配:不能从StringBuilder转换为String"

只是使用

 return ma.toString(); 

代替

 return ma; 

ma.toString()返回StringBuilder的string表示。

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

正如Valeri Atamaniouk在评论中所build议的那样,你也应该在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所build议的那样,我们在这个代码中有三种反模式

 } 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反模式的更多详细信息:

  • Java反模式
  • 编程反模式
  • Java应用程序中的反模式简介

在将StringBuilder转换为String时,我有同样的问题,我使用上面的点,但是这不是正确的解决scheme。 使用上面的代码输出是这样的

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

之后,我find了正确的解决scheme。认为是创build一个新的string即时插入StringBuilder像这样..

 String out=new String(ma);