java
JAVA - 파일 복사, 이동
파일을 복사하는 함수를 만들어 보겠습니다.
// ex.1)
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class Ex06 {
public Ex06() {
try {
String old_name = "src/aaa.txt";
String new_name = "bbb.txt";
// src/aaa.txt 파일을 읽어서
FileInputStream fin = new FileInputStream(old_name);
// bbb.txt 파일로 복사합니다.
FileOutputStream fout = new FileOutputStream(new_name);
int tmp = 0;
while ((tmp = fin.read()) != -1) {
fout.write(tmp);
}
fin.close();
fout.close();
}catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new Ex06();
}
}
다음은 파일을 이동시키는 함수를 만듭니다.
// ex.2)
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class Ex06 {
public Ex06() {
try {
String old_name = "src/aaa.txt";
String new_name = "bbb.txt";
// src/aaa.txt 파일을 읽어서
FileInputStream fin = new FileInputStream(old_name);
// bbb.txt 파일로 복사합니다.
FileOutputStream fout = new FileOutputStream(new_name);
int tmp = 0;
while ((tmp = fin.read()) != -1) {
fout.write(tmp);
}
fin.close();
fout.close();
// 복사가 완료되면 원본파일 old_name 을 삭제합니다.
File del = new File(old_name);
del.delete();
}catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new Ex06();
}
}
0 댓글