1. 程式人生 > >java實現檔案複製功能

java實現檔案複製功能

簡單的檔案複製程式,當然只是複製過程中的一部分,仔細分析還有很多功能,比如判斷磁碟是否有足夠空間,效率等問題,這些問題後面會牽涉到

public void copyFolder(String oldPath,String newPath){

File nf = new File(newPath);
if(!nf.exists()){//判斷檔案是否存在,不存在新建
nf.mkdirs();
}
File of = new File(oldPath);
String[] file = of.list();
File temp = null;
for(int i=0;i<file.length;i++){
if(oldPath.endsWith(File.separator)){
temp = new File(oldPath+file[i]);
}else{
temp = new File(oldPath+File.separator+file[i]);
}

if(temp.isFile()){
try {
FileInputStream fis = new FileInputStream(temp);
FileOutputStream fos = new FileOutputStream(newPath+"/"+temp.getName().toString());
byte[] by = new byte[1024*2];//一次讀取寬度
int len = 0;
while((len=fis.read(by))!=-1){
fos.write(by,0,len);
}
fos.flush();
fos.close();
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(temp.isDirectory()){
copyFolder(oldPath+"/"+file[i], newPath+"/"+file[i]);
}
}
}