– 버퍼 스트림
•문자 입력 스트림으로부터 문자를 읽어 들이거나
•문자 출력 스트림으로 문자를 내보낼 때 버퍼링을 함으로써
문자, 문자 배열, 문자열 라인 등을 보다 효율적으로 처리
예제1)
package io;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class ByteFileCopy {
public static void main(String[] args) throws IOException {
// 읽어올 대상 파일의 InputStream 인스턴스를 생성한다.
InputStream in = new FileInputStream("org.pdf");
// 출력 대상 파일의 OutpurStream 인스턴스 생성
OutputStream out = new FileOutputStream("org_copy.pdf");
// 필터스트림 인스턴스 생성
BufferedInputStream bin = new BufferedInputStream(in, 1024 * 3);
BufferedOutputStream bout = new BufferedOutputStream(out, 1024 * 3);
int copyByte = 0; // 복사한 사이즈
int bData = 0; // 원본에서 복사한 byte 사이즈의 데이터
System.out.println("복사를 시작합니다.");
while (true) {
bData = in.read(); // 더이상 가져올 데이터가 없으면 -1을 반환
if (bData == -1) {
break;
}
out.write(bData); // 출력 : 파일에 바이터리 코드를 쓴다.
copyByte++;
}
in.close(); // 스트림 인스턴스 소멸
out.close();
System.out.println("복사가 완료되었습니다.");
System.out.println("복사된 사이즈 : " + copyByte + "byte");
}
}
예제2)
package io;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class BufferedByteFileCopy {
public static void main(String[] args) throws IOException {
// 읽어올 대상 파일의 InputStream 인스턴스를 생성한다.
InputStream in = new FileInputStream("org.pdf");
// 출력 대상 파일의 OutpurStream 인스턴스 생성
OutputStream out = new FileOutputStream("org_copy.pdf");
int copyByte=0; // 복사한 사이즈
byte[] buf = new byte[1024]; // 1kb 버퍼생성
int readLength = 0; // 얼마만큼 읽어왔는지.
System.out.println("복사를 시작합니다.");
while(true) {
readLength = in.read(buf);
if(readLength==-1) {
break;
}
out.write(buf,0,readLength);
copyByte+= readLength;
}
in.close(); // 스트림 인스턴스 소멸
out.close();
System.out.println("복사가 완료되었습니다.");
System.out.println("복사된 사이즈 : " + copyByte + "byte");
}
}
'JAVA > basic' 카테고리의 다른 글
[ 네트워크 ] 소켓 / Socket 클래스 (0) | 2020.10.28 |
---|---|
[ 네트워크 ] URL (0) | 2020.10.28 |
스레드 / 쓰레드 / thread (0) | 2020.10.27 |
[ 입출력 ] File (0) | 2020.10.26 |
[ 입출력 ] 직렬화 (Serializable) (0) | 2020.10.26 |
[ 입출력 ] 문자스트림 : BufferedWriter / BufferedReader / PrintWriter (0) | 2020.10.26 |
[ 입출력 ] Stream / 바이트스트림 (0) | 2020.10.26 |