Java로 파일 복사하기: FileInputStream과 FileOutputStream

Soozoo·2024년 6월 26일

JAVA

목록 보기
26/41

주요 클래스와 메서드

  1. FileInputStream: 파일로부터 바이트 스트림을 읽어오는 클래스입니다.

    1. FileOutputStream: 파일에 바이트 스트림을 쓰는 클래스입니다.
    2. System.currentTimeMillis(): 현재 시간을 밀리초 단위로 반환하는 메서드로, 파일 복사에 걸린 시간을 측정하는 데 사용됩니다.

    코드 설명

    다음은 파일을 복사하는 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!!");
    	}
    }

    코드 설명

    1. 파일 읽기 객체 생성
      • InputStream is = new FileInputStream("dog.jpg");: FileInputStream을 사용하여 "dog.jpg" 파일을 읽기 위한 입력 스트림을 생성합니다.
    2. 파일 쓰기 객체 생성
      • OutputStream os = new FileOutputStream("dogcopy.jpg");: FileOutputStream을 사용하여 "dogcopy.jpg" 파일을 쓰기 위한 출력 스트림을 생성합니다.
    3. 복사 시작 시간 측정
      • long start = System.currentTimeMillis();: 복사 시작 시간을 밀리초 단위로 저장합니다.
    4. 파일 복사 루프
      • while (true): 무한 루프를 시작합니다.
      • int inputData = is.read();: 입력 스트림으로부터 한 바이트를 읽습니다. 더 이상 읽을 데이터가 없으면 -1을 반환합니다.
      • if (inputData == -1) break;: 데이터가 없으면 루프를 종료합니다.
      • os.write(inputData);: 읽은 바이트를 출력 스트림에 씁니다.
    5. 복사 종료 시간 측정 및 출력
      • long end = System.currentTimeMillis();: 복사 종료 시간을 밀리초 단위로 저장합니다.
      • System.out.println("Time taken: " + (end - start) + " ms");: 복사에 걸린 시간을 출력합니다.
    6. 스트림 닫기
      • is.close();: 입력 스트림을 닫습니다.
      • os.close();: 출력 스트림을 닫습니다.
    7. 복사 성공 메시지 출력
      • System.out.println("Copy success!!");: 복사가 완료되었음을 알리는 메시지를 출력합니다.
profile
넙-죽

0개의 댓글