자바로 파일을 복사하는 프로그램을 코딩해보자.
1) 잘못된 예
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class FileCopyEx1 {
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// 키보드로 입력을 받는다.
String source, dest;
FileOutputStream fos = null;
FileInputStream fis = null;
try {
System.out.print("복사할 원본 파일명 ? ");
source = br.readLine();
System.out.print("복사시킬 대상 파일명 ? ");
dest = br.readLine();
fis = new FileInputStream(source);
fos = new FileOutputStream(dest);
// 잘못 코딩한 예 - 서울에서 부산을 걸어서 가는 꼴
int data;
while( (data = fis.read()) != -1) {
fos.write(data);
}
fos.flush();
System.out.println("파일 복사 완료...");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if ( fis != null) {
try {
fis.close();
} catch (Exception e2) {
}
}
if ( fos != null) {
try {
fos.close();
} catch (Exception e2) {
}
}
}
}
}
2) 효율적인 방식
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class FileCopyEx2 {
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// 키보드로 입력을 받는다.
String source, dest;
FileOutputStream fos = null;
FileInputStream fis = null;
byte[] b = new byte[4096];
int len;
try {
System.out.println("파일 복사...");
System.out.print("복사할 원본 파일명 ? ");
source = br.readLine();
System.out.print("복사시킬 대상 파일명 ? ");
dest = br.readLine();
fis = new FileInputStream(source);
fos = new FileOutputStream(dest);
long s = System.currentTimeMillis();
// len = fis.read(b) => 최대 바이트배열 b길이 만큼 읽어 b에 저장하고
// 실제로 읽어 들인 byte수를 반환
while( (len = fis.read(b)) != -1) {
fos.write(b, 0, len); // b배열의 0번째 인덱스부터 len개 저장
}
fos.flush();
long e = System.currentTimeMillis();
System.out.println("파일 복사 완료..." + (e-s)+"ms");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if ( fis != null) {
try {
fis.close();
} catch (Exception e2) {
}
}
if ( fos != null) {
try {
fos.close();
} catch (Exception e2) {
}
}
}
}
}
ABCDEF 가 파일에 있어서 이 문자들을 읽어서 다른 파일에 붙일때, A를 읽으면 다시 A를 읽지 않는다.
읽은 것은 다시 읽지 않는다! 그래서 배열에 인덱스 없이도 알아서 다 들어갔다가 다음 배열에 또 들어가고 그렇게 되는 것이다.
'쌍용강북교육센터 > 8월' 카테고리의 다른 글
0823_Java : FileOutputStream 클래스 (0) | 2021.08.24 |
---|---|
0823_Java : FileWriter, FileReader 클래스 (0) | 2021.08.24 |
0823_Java : FileInputStream 클래스 (0) | 2021.08.24 |
0823_Java : FileOutStream 클래스 (0) | 2021.08.24 |
0823_Java : BufferedReader 클래스 (0) | 2021.08.24 |