Jan 1, 0001 · 85 words · 1 minute read

Title: InputStreamをStringに変換する Date: 2012-03-01 00:00 Slug: java-inputstream-to-string Tags: 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();
}