1. 程式人生 > 其它 >將一個資料夾的文件複製到另一個資料夾

將一個資料夾的文件複製到另一個資料夾

package test05;

import java.io.*;

public class test080702 {
public static void main(String[] args) {
copy_1();
copy_2();
}

//第二種:以字元陣列方式複製。
public static void copy_2() {
FileWriter fw=null;
FileReader fr=null;
try {
fw=new FileWriter("D:\\Java練習\\test0804_copy_2.txt");
fr=new FileReader("D:\\Java練習\\test05\\src\\test05\\test0804.java");
char[] buf=new char[1024];
int len=0;
long start=System.currentTimeMillis();
while((len=fr.read(buf))!=-1) {
fw.write(buf,0,len);
}
long end=System.currentTimeMillis();
System.out.println("陣列方式耗時為:"+(end-start));
}catch(IOException e) {
throw new RuntimeException("複製失敗");
}finally {
try {
if(fw!=null)
fw.close();
}catch(IOException e) {
System.out.println(e.toString());
}finally {
try {
if(fr!=null)
fr.close();
}catch(IOException e) {
System.out.println(e.toString());
}
}
}
}

//第一種方式:以單個位元組方式複製。
public static void copy_1() {
FileWriter fw=null;
FileReader fr=null;
try {
fw=new FileWriter("D:\\Java練習\\test0804_copy_1.txt");
fr=new FileReader("D:\\Java練習\\test05\\src\\test05\\test0804.java");
int ch=0;
long start=System.currentTimeMillis();
while((ch=fr.read())!=-1) {
fw.write(ch);
}
long end=System.currentTimeMillis();
System.out.println("位元組方式耗時為:"+(end-start));
}catch(IOException e) {
System.out.println(e.toString());
}finally {
try {
if(fw!=null)
fw.close();
}catch(IOException e) {
System.out.println(e.toString());
}
try {
if(fr!=null) {
fr.close();
}
}catch(IOException e) {
System.out.println(e.toString());
}
}
}
}