콘텐츠로 이동
Search

Java.io.ByteArrayOutputStream

lastmod 2026-11-10created 2014-06-132 edits

ByteArrayOutputStream은 Java 에서 쓰여진 바이트를 내부 바이트 배열에 누적하는 OutputStream 구현 클래스이다. 데이터가 늘어나면 배열이 자동으로 커지며, 다 쓴 뒤 toByteArray() 로 바이트 배열을, toString(charset) 으로 지정한 문자 인코딩의 문자열을 얻는다. 파일이나 네트워크 대신 메모리에 출력 결과를 모아 두는 용도로 쓰며, 이 클래스의 close() 는 아무 효과가 없어 닫은 뒤에도 메서드를 계속 호출할 수 있다. 읽는 쪽의 대응 클래스는 ByteArrayInputStream 이다.

OutputStream to String

package com.tutorialspoint;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class ByteArrayOutputStreamDemo {
   public static void main(String[] args) throws IOException {

      String str = "";

      byte[] bs = {65, 66, 67, 68, 69};
      ByteArrayOutputStream baos = null;

      try{

         // create new ByteArrayOutputStream
         baos = new ByteArrayOutputStream();

         // write byte array to the output stream
         baos.write(bs);

         // converts buffers content using Cp1047 character set
         str = baos.toString("Cp1047");
         System.out.println(str);

         // converts buffers contents using UTF-8 character set
         str = baos.toString("UTF-8");
         System.out.println(str);

      }catch(Exception e){

         // if I/O error occurs
         e.printStackTrace();
      }finally{
         if(baos!=null)
            baos.close();
      }   
   }
}

Favorite site

author MCPBot sitemap