FileInputStream: 파일로부터 바이트 스트림을 읽어오는 클래스입니다.
다음은 파일을 복사하는 Java 프로그램의 코드입니다:
package ex06.filecopy;
import java.io.*;
public class FileCopy{
public static void main(String[] args) throws IOException{
//읽기 객체 - FileInputStream
//InputStream is =new FileInputStream("dog.jpg"); //상대경로
InputStream is =new FileInputStream("C:\\Users\\user\\eclipse-workspace\\JavaS\\ex03.IO/dog.jpg"); //절대경로
//쓰기 객체 - FileOutputStream
//OutputStream os =new FileOutputStream("dogcopy00.jpg");
OutputStream os =new FileOutputStream("C:\\Users\\user\\Desktop\\Quiz/dog00.jpg"); //절대경로
byte[] buffer =new byte[1024 * 8]; // 속도 처리 향상
long start = System.currentTimeMillis(); //시작시간저장
while(true) {
int inputData =is.read(buffer);
if(inputData == -1) break;
os.write(buffer, 0, inputData);
}
long end =System.currentTimeMillis(); //끝난시간저장
System.out.println(end - start);
is.close(); os.close();
System.out.println("copy success!!");
}
}
InputStream is = new FileInputStream("dog.jpg");: FileInputStream을 사용하여 "dog.jpg" 파일을 읽기 위한 입력 스트림을 생성합니다.OutputStream os = new FileOutputStream("dogcopy.jpg");: FileOutputStream을 사용하여 "dogcopy.jpg" 파일을 쓰기 위한 출력 스트림을 생성합니다.long start = System.currentTimeMillis();: 복사 시작 시간을 밀리초 단위로 저장합니다.while (true): 무한 루프를 시작합니다.int inputData = is.read();: 입력 스트림으로부터 한 바이트를 읽습니다. 더 이상 읽을 데이터가 없으면 -1을 반환합니다.if (inputData == -1) break;: 데이터가 없으면 루프를 종료합니다.os.write(inputData);: 읽은 바이트를 출력 스트림에 씁니다.long end = System.currentTimeMillis();: 복사 종료 시간을 밀리초 단위로 저장합니다.System.out.println("Time taken: " + (end - start) + " ms");: 복사에 걸린 시간을 출력합니다.is.close();: 입력 스트림을 닫습니다.os.close();: 출력 스트림을 닫습니다.System.out.println("Copy success!!");: 복사가 완료되었음을 알리는 메시지를 출력합니다.