연습 문제1
C:\storage\prac1.txt 파일을 1글자씩 읽어서 C:\storage\prac1_copy.txt 파일로 보내고 걸린 시간 출력하기
- FileWriter, FileReader 사용, int read() 메소드 사용
File src = new File("C:\\storage", "prac1.txt");
File cpy = new File("C:\\storage", "prac1_copy.txt");
FileReader fr = null;
FileWriter fw = null;
try {
fr = new FileReader(src);
fw = new FileWriter(cpy);
int c;
long begin = System.currentTimeMillis();
while((c = fr.read()) != -1) {
fw.write(c);
}
long end = System.currentTimeMillis();
System.out.println("복사시간 : " + (end - begin) * 0.001 + "초");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(fw != null) fw.close();
if(fr != null) fr.close();
} catch(IOException e) {
e.printStackTrace();
}
연습 문제2
연습 문제 1 BufferedReader, BufferedWriter 사용해서 다시 풀기
(100글자씩 읽어서 보내기)
File src = new File("C:\\storage", "prac1.txt");
File cpy = new File("C:\\storage", "prac1_copy.txt");
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader(src));
bw = new BufferedWriter(new FileWriter(cpy));
char[] cbuf = new char[100];
int readCnt = 0;
long begin = System.currentTimeMillis();
while((readCnt = br.read(cbuf)) != -1) {
bw.write(cbuf, 0, readCnt);
}
long end = System.currentTimeMillis();
System.out.println("복사시간 : " + (end - begin) * 0.001 + "초");
} catch(IOException e) {
e.printStackTrace();
} finally {
try {
if(bw != null) bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
연습 문제3
이클립스 파일 복사하기, 복사한 파일 삭제하기
File src = new File("C:\\GDJ\\installer", "eclipse-jee-2021-03-R-win32-x86_64.zip");
File cpy = new File("C:\\GDJ\\installer", "eclipse.zip");
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(src));
bos = new BufferedOutputStream(new FileOutputStream(cpy));
byte[] b = new byte[1024]; // 1KB
int readByte = 0;
while((readByte = bis.read(b)) != -1) {
bos.write(b, 0, readByte);
}
} catch(IOException e) {
e.printStackTrace();
} finally {
try {
if(bos != null) bos.close();
if(bis != null) bis.close();
} catch(IOException e) {
e.printStackTrace();
}
}
File dir = new File("C:\\storage");
if(dir.exists() == false) {
dir.mkdirs();
}
File src = new File("C:\\GDJ\\installer", "eclipse.zip");
File dst = new File(dir, src.getName());
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(src));
bos = new BufferedOutputStream(new FileOutputStream(dst));
byte[] b = new byte[1024];
int readByte = 0;
while((readByte = bis.read(b)) != -1) {
bos.write(b, 0, readByte);
}
bos.close();
bis.close();
// 원본과 복사본의 크기가 동일하면 원본을 제거
if(src.length() == dst.length()) {
src.deleteOnExit();
}
} catch(IOException e) {
e.printStackTrace();
}