안 씀/java-개념

파일 입출력 응용: 파일 복사

unhyepnhj 2024. 6. 24. 16:44

텍스트 파일 복사

- 문자 스트림을 이용하여 텍스트 파일 복사

//예제 8-9

import java.io.*;

public class TextCopyEx {
	public static void main(String[] args) {
		File src=new File("c:\\Windows\\system.ini");	//원본 파일 경로명
		File dest=new File("c:\\Temp\\system.txt");	//복사 파일 경로명
		
		int c;
		try {
			FileReader fr=new FileReader(src);	//파일 입력 문자 스트림 생성
			FileWriter fw=new FileWriter(dest);	//파일 출력
			
			while((c=fr.read())!=-1) 
				fw.write((char)c);
			
			fr.close();
			fw.close();
			System.out.println(src.getPath()+"를 "+dest.getPath()+"로 복사하였습니다.");
		}
		catch(IOException e) {
			System.out.println("파일 복사 오류");
		}
	}
}

- FileReader로 텍스트 파일을 읽고 FileWriter로 텍스트 파일에 복사

- File 객체를 이용하여 파일 경로명 추출

- 해당 방식으로는 텍스트 파일 외 파일(이미지나 워드, PPT, 한글(.hwp)파일 등)들을 복사할 수 없음


바이너리 파일 복사

- 바이트 스트림을 이용하여 바이너리 파일 복사

//예제 8-10

import java.io.*;

public class BinaryCopyEx {
	public static void main(String[] args) {
		File src=new File("c:\\Windows\\Web\\Wallpaper\\Theme1\\img1.img");	//원본 파일 경로명
		File dest=new File("c:\\Temp\\copyimg.jpg");	//복사 파일 경로명
		
		int c;
		try {
			FileInputStream fin=new FileInputStream(src);
			FileOutputStream fout=new FileOutputStream(dest);
			
			while((c=fin.read())!=-1)
				fout.write((byte)c);
			
			fin.close();
			fout.close();
			System.out.println(src.getPath()+"를 "+dest.getPath()+"로 복사하였습니다.");
		}
		catch(IOException e) {
			System.out.println("파일 복사 오류");
		}
	}
}

- 이미지 파일 복사

- 한 바이트씩 복사하므로 소요 시간 증가


블록 단위로 파일 고속 복사

- 복사 속도를 높이기 위해 BufferedInputStream/BufferedOutputStream을 사용하거나 블록 단위로 읽고 쓰도록 수정

//예제 8-11

import java.io.*;

public class BlockBinaryCopyEx {

	public static void main(String[] args) {
		File src=new File("c:\\Windows\\Web\\Wallpaper\\Theme1\\img1.jpg");	//원본
		File dest=new File("c:\\Temp\\desert.jpg");	//복사
		try {
			FileInputStream fin=new FileInputStream(src);
			FileOutputStream fout=new FileOutputStream(dest);
			byte[] buf=new byte[2014*10];	//10KB 버퍼
			while(true) {
				int n=fin.read(buf);		//버퍼 크기만큼 읽기(n=실제 읽은 바이트)
				fout.write(buf, 0, n);	//buf[0]부터 n바이트 쓰기
				if(n<buf.length) break;	//버퍼 크기보다 작게 읽으면 파일 끝에 도달, 복사 종료
			}
			fin.close();
			fout.close();
			System.out.println(src.getPath()+"를 "+dest.getPath()+"로 복사하였습니다.");
		}
		catch(IOException e) {
			System.out.println("파일 복사 오류");
		}
	}
}

- 예제 8-10을 10KB 단위로 읽고 쓰도록 수정하여 고속 복사