InputStreamをStringに変換する

Mar 1, 2012 · 76 words · 1 minute read Java

いつも忘れるからメモ

改行を無視する

public String convertString(InputStream is) 
        throws IOException {
    BufferedReader reader = 
        new BufferedReader(new InputStreamReader(is, "UTF-8"));
    StringBuilder sb = new StringBuilder();
    String line;
    while (null != (line = reader.readLine())) {
        sb.append(line);
    }
    return sb.toString();
}

改行も含める

public String convertString(InputStream is)
        throws IOException {
    BufferedReader reader =
        new BufferedReader(new InputStreamReader(is, "UTF-8"));
    StringBuilder sb = new StringBuilder();
    char[] b = new char[1024];
    int line;
    while (0 <= (line = reader.read(b))) {
        sb.append(b, 0, line);
    }
    return sb.toString();
}