Tag Archives: Java InputStream

[Source | Java] InputStream to String

Java에서 InputStream객체를 String으로 변환하는 코드를 정리한다.


작성일 : 2021-04-23


// Define
InputStream is = {SomeData};

1> BufferedReader 객체사용

InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
StringBuffer sb = new StringBuffer();
String line;
while((line = br.readLine()) != null) {
	sb.append(line);
	sb.append('\r');
}
br.close();
// Result
String str = sb.toString();

2> StringBuffer 객체사용

StringBuffer sb = new StringBuffer();
byte[] b = new byte[4096];
int length;
while((length = is.read(b)) != -1) {
	sb.append(new String(b, 0, length));
}
// Result
String str = sb.toString();

3>  ByteArrayOutputStream 객체사용

ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] b = new byte[4096];
int length;
while((length = is.read(b)) != -1) {
	baos.write(b, 0, length);
}
baos.flush();
// Result
String str = new String(baos.toByteArray());