I'm tired of going around every time I need it, so I'll keep it as a memo for myself (´ ・ ω ・ `)
If you want to read all InputStream
and convert it to String
, you can write roughly as follows.
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();
}
If the character code of InputStream
that you want to convert to String
is not UTF-8, you can use ByteArrayOutputStream.toString (Charset charset)
. For example, if InputStream
is Windows-31J, write as follows.
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"));
}
In order to avoid reinventing the wheel, if you can use the OSS library such as IOUtils of Apache Commons, use that (´ ・ ω ・ `)
** Environmental Information: **
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)
Recommended Posts