LoginSignup
1
1

More than 3 years have passed since last update.

InputStreamをStringに変換したい

Posted at

必要になるたびにぐぐるのに疲れたので自分用のメモとしておいておきますね(´・ω・`)

InputStreamをすべて読み込んでStringに変換したい場合、おおよそ以下のように書いておけば大丈夫です。

public static String readAll(InputStream in) throws IOException {
    byte[] b = new byte[1024];
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    int len;
    while ((len = in.read(b)) != -1) {
        out.write(b, 0, len);
    }
    return out.toString();
}

またStringに変換したいInputStreamの文字コードがUTF-8ではない場合、ByteArrayOutputStream.toString(Charset charset)を利用すればよいです。たとえばInputStreamがWindows-31Jの場合は以下のように書きます。

public static String readAll(InputStream in) throws IOException {
    byte[] b = new byte[1024];
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    int len;
    while ((len = in.read(b)) != -1) {
        out.write(b, 0, len);
    }
    return out.toString(Charset.forName("Windows-31J"));
}

なお車輪の再発明を避ける意味でも、Apache CommonsのIOUtilsなど、OSSのライブラリが使える場合はそちらを使いましょう(´・ω・`)

環境情報:

C:\>javac -version
javac 11.0.3
C:\>java -version
openjdk version "11.0.3" 2019-04-16
OpenJDK Runtime Environment AdoptOpenJDK (build 11.0.3+7)
OpenJDK 64-Bit Server VM AdoptOpenJDK (build 11.0.3+7, mixed mode)
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1