English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
이 튜토리얼에서는 예제를 통해 Java BufferedOutputStream 및 메서드를 배웁니다.
java.io 패키지의 BufferedOutputStream 클래스는 데이터(바이트 단위로)를 더 효율적으로 쓰기 위해 다른 출력 스트림과 함께 사용됩니다.
OutputStream 추상 클래스를 상속합니다.
BufferedOutputStream은8192바이트의 내부 버퍼.
쓰기 작업 중에는 바이트가 디스크 대신 내부 버퍼에 쓰입니다. 버퍼가 가득 차거나 스트림이 닫히면 전체 버퍼가 디스크에 쓰입니다.
따라서 디스크와의 통신 횟수가 줄어듭니다. 이것이 BufferedOutputStream를 사용하여 바이트를 쓰는 것이 더 빠른 이유입니다.
BufferedOutputStream를 생성하기 위해 먼저 java.io.BufferedOutputStream 패키지를 가져와야 합니다. 패키지를 가져온 후에는 출력 스트림을 생성할 수 있습니다.
//FileOutputStream를 생성합니다. FileOutputStream file = new FileOutputStream(String path); //BufferedOutputStream을 생성하십시오. BufferedOutputStream buffer = new BufferedOutputStream(file);
위의 예제에서는 buffer라는 이름의 BufferedOutputStream를 생성하고 file라는 FileOutputStream을 사용했습니다.
이곳에서 내부 버퍼의 기본 크기는8192바이트는 그렇지만, 우리는 내부 버퍼의 크기를 지정할 수도 있습니다.
//지정된 크기의 내부 버퍼를 가진 BufferedOutputStream를 생성합니다. BufferedOutputStream buffer = new BufferedOutputStream(file, int size);
이 버퍼는 파일에 바이트를 더 빠르게 쓰는 데 도움이 됩니다.
BufferedOutputStream 클래스는 OutputStream 클래스의 다양한 메서드를 구현 제공합니다.
write() - 단일 바이트를 출력 스트림의 내부 버퍼에 쓰기
write(byte[] array) - 지정된 배열의 바이트를 출력 스트림에 쓰기
write(byte[] arr, int start, int length)- start 위치에서 length 길이의 바이트를 배열의 출력 스트림에 쓰기
import java.io.FileOutputStream; import java.io.BufferedOutputStream; public class Main { public static void main(String[] args) { String data = "This is a line of text inside the file"; try { //FileOutputStream를 생성합니다. FileOutputStream file = new FileOutputStream("output.txt"); //BufferedOutputStream을 생성하십시오. BufferedOutputStream output = new BufferedOutputStream(file); byte[] array = data.getBytes(); //데이터를 출력 스트림에 쓰기 output.write(array); output.close(); } catch(Exception e) { e.getStackTrace(); } } }
위 예제에서는 output라는 버퍼화된 출력 스트림과 FileOutputStream를 생성했습니다. 출력 스트림은 output.txt 파일과 연결되었습니다.
FileOutputStream file = new FileOutputStream("output.txt"); BufferedOutputStream output = new BufferedOutputStream(file);
데이터를 파일에 쓰기 위해 write() 메서드를 사용했습니다.
프로그램을 실행할 때,output.txt파일에 다음 내용이 쓰여질 것입니다.
This is a line of text inside the file.
주의: 문자열을 바이트 배열로 변환하는 getBytes() 메서드를 사용합니다.
내부 버퍼를 비우기 위해 flush() 메서드를 사용할 수 있습니다. 이 메서드는 버퍼에 있는 모든 데이터를 강제로 목표 파일에 쓰도록 합니다. 예를 들어,
import java.io.FileOutputStream; import java.io.BufferedOutputStream; public class Main { public static void main(String[] args) { String data = "This is a demo of the flush method"; try { //FileOutputStream를 생성합니다. FileOutputStream file = new FileOutputStream("flush.txt"); //BufferedOutputStream을 생성하십시오. BufferedOutputStream buffer = new BufferedOutputStream(file); //데이터를 출력 스트림에 쓰기 buffer.write(data.getBytes()); //데이터를 목표로 전달하려면 buffer.flush(); System.out.println("데이터가 파일로 전달됩니다."); buffer.close(); } catch(Exception e) { e.getStackTrace(); } } }
출력 결과
데이터가 파일로 전달됩니다.
프로그램을 실행할 때, flush.txt 파일은 문자 데이터로 표시된 텍스트로 채워집니다.
버퍼드 출력 스트림을 닫으려면 close() 메서드를 사용할 수 있습니다. 이 메서드를 호출한 후에는 출력 스트림에 데이터를 쓰는 것이 불가능합니다.