1. 程式人生 > >IO流-檔案的拷貝、刪除

IO流-檔案的拷貝、刪除

一、IO流方法

   1)拷貝檔案、資料夾

   2)刪除檔案、資料夾

二、程式碼實現

 1)拷貝檔案、資料夾 

// 從任意已知目錄拷貝所有檔案到另一目錄
public static void copyAll(File srcFile, File destFile) throws Exception {
if (srcFile.exists()) {
if (!destFile.exists()) {
destFile.mkdirs();
}
File[] file = srcFile.listFiles();
InputStream is = null;
OutputStream os = null;
for (File f : file) {

if (f.isFile()) {
is = new FileInputStream(f);
os = new FileOutputStream(new File(destFile, f.getName()));
int len = 0;
byte[] byt = new byte[1024];
while (-1 != (len = is.read(byt))) {
os.write(byt, 0, len);
}
try {
os.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
}
} else {
copyAll(f, new File(destFile, f.getName()));

}
}
} else {
System.out.println("原始檔不存在");
}
}

   2)刪除檔案、資料夾

//刪除指定檔案下的資料夾和檔案

public static void delFile(File file){

if(file.exists()){

File[] flist=file.listFiles();

for(File f:flist){

if(f.isFile()){

f.delete();

}else{

delFile(f);

}

}

//當資料夾中檔案全部刪除後,再刪除空資料夾

file.delete();

}else{

System.out.println("原檔案不存在");

}

}

三、注意

 1)程式碼可以使用,但是自己注意在main中呼叫下。