27

このメソッドは、指定された 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

そして2つの選択肢:

  1. Change the return type to StringBuilder. しかし、私はそれが文字列を返すことを望んでいます。
  2. Change type of ma to String. String を変更した後、append() メソッドはありません。
4

3 に答える 3

54

使うだけ

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
}

良い考えでしょう。


編集

Esailja が示唆したように、このコードには 3 つのアンチパターンがあります。

} 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 アンチパターンの詳細については、次のリンクを確認してください。

于 2013-04-22T20:09:30.807 に答える
3

StringBuilder を String に変換するときに同じ問題があり、上記のポイントを使用していますが、正しい解決策ではありません。上記のコード出力を使用すると、次のようになります

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

その後、私は正しい解決策を見つけます.Thinkは、このようにStringBuilderの挿入された新しいStringインスタントを作成することです..

String out=new String(ma);
于 2017-02-24T06:47:41.537 に答える