대상 파일: a.pptx
사본 이름: d.pptx
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Scanner;
public class FileCopy {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("대상 파일 : ");
String src = sc.nextLine();
System.out.print("사본 이름 : ");
String dst = sc.nextLine();
try (InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst)) {
// int data;
byte buf[] = new byte[1024];
int len;
while (true) {
// data = in.read(); //Read 1byte from the File
len = in.read(buf);
// if (data == -1)
if (len ==-1)
{ // If when there is no more data to read
break;
}
// out.write(data); // 1byte is written to the file.
out.write(buf, 0, len);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
자바에서는 파일이나 콘솔의 입출력을 직접 다루지 않고, 스트림(stream)이라는 흐름을 통해 다룬다.
스트림(stream)이란 실제의 입력이나 출력이 표현된 데이터의 이상화된 흐름을 의미한다.
즉, 스트림은 운영체제에 의해 생성되는 가상의 연결 고리를 의미하며, 중간 매개자 역할을 한다.
read() 메소드는 해당 입력 스트림에서 더 이상 읽어들일 바이트가 없으면, -1을 반환해야 한다.
그런데 반환 타입을 byte 타입으로 하면, 0부터 255까지의 바이트 정보는 표현할 수 있지만 -1은 표현할 수 없게 된다.
따라서 InputStream의 read() 메소드는 반환 타입을 int형으로 선언하고 있다.