[컴][자바] InputStream 을 String 으로 바꾸기

Java에서 InputStream 을 String 으로 바꾸기 / StringBuffer 로 바꾸기


ByteArrayOutputStream 을 이용한 방법

InputStream is = ...

ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[16384];
while( (nRead = is.read(data)) != -1 ) {
 buffer.write(data, 0, nRead);
}
buffer.flush();

String str = new String(buffer.toByteArray());



StringBuffer 를 이용한 방법

int i;
InputStream is = new FileInputStream("C:/file.txt");
StringBuffer buffer = new StringBuffer();
byte[] b = new byte[4096];
while( (i = is.read(b)) != -1){
 buffer.append(new String(b, 0, i));
}
String str = buffer.toString();


BufferedReader 를 사용하는 방법

URL feedUrl = new URL(feed);
InputStream is = feedUrl.openConnection().getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer(); 
while((line = rd.readLine()) != null) {
 response.append(line);
 response.append('\r');
}
rd.close();



References

  1. http://www.coderanch.com/t/276921/Streams/java/help-inputstream-String-or-StringBuffer
  2. http://www.roseindia.net/tutorial/java/core/files/convertInputStreamToString.html

댓글 없음:

댓글 쓰기