개발_웹/Java
Java | 파일 복사하기 (텍스트, 바이너리)
zuyo
2019. 5. 11. 15:19
반응형
1. 텍스트 파일 복사
public class FileIO {
public static void main(String[] args) {
try {
// 파일 객체 생성
File original = new File("D:\\original.txt");
File copy = new File("D:\\copy.txt");
// 스트림 생성
FileReader fileReader = new FileReader(original);
FileWriter fileWriter = new FileWriter(copy);
// 파일 복사
int singleCh = 0;
// 파일의 끝에 도달 할 때까지 character 하나씩 읽어들임
while((singleCh = fileReader.read()) != -1) {
fileWriter.write(singleCh);
}
// 스트림 닫기
fileWriter.close();
fileReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2. 바이너리 파일 복사 (버퍼 사용)
public class FileIO2 {
public static void main(String[] args) {
try {
// 파일 객체 생성
File original = new File("D:\\original.jpg");
File copy = new File("D:\\copy.jpg");
// 스트림 생성
FileInputStream fileInputStream = new FileInputStream(original);
FileOutputStream fileOutputStream = new FileOutputStream(copy);
// 버퍼 생성
byte[] buf = new byte[5000];
// 파일 복사
int readData = 0;
// 파일의 끝에 도달할 때까지 버퍼의 크기만큼 읽어들임 (버퍼의 0번째 인덱스부터 버퍼 크기만큼)
while((readData = fileInputStream.read(buf, 0, buf.length)) != -1) {
fileOutputStream.write(buf, 0, readData); // 쓰기
}
// 스트림 닫기
fileInputStream.close();
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
반응형