개인참고자료/자바(네트워크)

바이트 기반 스트림 - 파일 복사

경진 2008. 7. 13. 17:00
파일 복사 

FileInputStream과 FileOutputStream을 이용해서 파일을 복사하는 프로그램이다.

import java.io.*;

public class FileStreamCopy {

    public static void main(String[] args) {
        if(args.length != 2){
            System.out.println("사용법 : java FileStreamCopy 파일1 파일2");
            System.exit(0);
        } // if end

        FileInputStream fis = null;
        FileOutputStream fos = null;
        try{
            fis = new FileInputStream(args[0]);
            fos = new FileOutputStream(args[1]);
            byte[] buffer = new byte[512];
            int readcount = 0;
            while((readcount = fis.read(buffer)) != -1){
                fos.write(buffer,0,readcount);
            }
            System.out.println("복사가 완료되었습니다.");

        }catch(Exception ex){
            System.out.println(ex);
        }finally{
            try {
                fis.close();
            } catch (IOException ex) {}
            try {
                fos.close();
            } catch (IOException ex) {}
        }
    } // main
}

        FileInputStream fis = null;
        FileOutputStream fos = null;

파일로부터 읽어 들이려고 FileInputStream을 선언하고, 파일에 쓰려고 FileOutputStream을 선언한다. 물론 try 블록에서 선언해야만 finally에서 선언된 변수를 사용할 수 있다.

            fis = new FileInputStream(args[0]);
            fos = new FileOutputStream(args[1]);
            byte[] buffer = new byte[512];
            int readcount = 0;
            while((readcount = fis.read(buffer)) != -1){
                fos.write(buffer,0,readcount);
            }
            System.out.println("복사가 완료되었습니다.");

첫번째 인자인 arg[0]은 FileInputStream의 생성자에 전달하고, 두 번째 인자인 arg[1]은 FileOutputStream의 생성자에 전달했다. 즉, 첫 번째 인자로 전달된 파일로부터 읽어 들여, 두 번째 인자로 전달된 파일에 쓰는 것을 알 수 있다.

바이트 배열에 read() 메소드로 읽어 들인 값을 저장한 후, write() 메소드를 이용해서 출력한다.
이전 파일 내용을 읽어 들여 화면에 출력하는 것과 소스가 흡사하다. FileOutputStream에 있는 write() 메소드와 System.out에 있는 write() 메소드는 모두 OutputStream에 있는 write() 메소드가 사용되기 때문이다.

결과화면