Java-拷貝資料夾
阿新 • • 發佈:2019-02-09
用Java程式碼編寫一個實現拷貝資料夾的功能
思路:
1、先在目的路徑建立一個與要被拷貝資料夾名相同名字的資料夾
2、將原資料夾中的所有成員(包括子資料夾以及檔案)遍歷一遍,並同時判斷每一個成員是否為檔案;是檔案則複製檔案到指定的目的路徑中;如不是,則此成員為子資料夾,就重新進行思路2,此處運用遞迴思想;
思路補充:
我門先將複製檔案的程式碼寫出封裝成一個函式,本文命名為copy( ) ,再建立一個拷貝所有檔案的函式,本文命名為copyPlus( );在copyPlus( )函式中第一步先將原資料夾中的所有成員(包括子資料夾以及檔案)遍歷一遍,並同時判斷每一個成員是否為檔案;是檔案則呼叫copy( )函式複製檔案到指定的目的路徑中;如不是,則此成員為子資料夾,就重新執行copyPuls( )函式,此處運用遞迴思想;
具體程式碼如下:
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
public class CopyPlus {
public static void main(String[] args) {
//copyPlus() 方法是將指定的資料夾(包含其中所有的檔案及子資料夾)拷貝到目的目錄
//此處傳參解釋:第一個String引數為被拷貝資料夾的全路徑,第二個String引數為拷貝到的目的路徑,將原檔案拷貝到D:\\java\\copy1中去
copyPlus("D:\\java\\copy\\copystart","D:\\java\\copy1");
}
private static void copyPlus(String src , String endsrc) {
//建立原資料夾的路徑和目的資料夾的路徑所對應的File物件
File file = new File(src);
File endfile = new File(endsrc+"\\\\"+file.getName());
//先將目的資料夾建立好,後續將裡面的檔案及子資料夾拷貝進去
endfile.mkdirs();
//用for迴圈遍歷原資料夾中的子資料夾及檔案
for (File f : file.listFiles()) {
//判斷依次迴圈遍歷出來的是子資料夾還是檔案
if(f.isFile()){
//是檔案的話,將呼叫copy()方法,將此檔案拷貝到對應的目的路徑中去
copy(f.getAbsolutePath(),endfile.getAbsolutePath()+"\\\\"+f.getName());
}else{
//是子資料夾的話,將呼叫copyPlus()方法,運用遞迴思想重新在其對應位置建立一個資料夾(包含這個資料夾中的所有檔案以及子資料夾)
copyPlus(f.getAbsolutePath(),endfile.getAbsolutePath());
}
}
}
private static void copy(String src,String endsrc) {
BufferedInputStream dis = null;
BufferedOutputStream dos = null;
try {
FileInputStream fis = new FileInputStream(src);
FileOutputStream fos = new FileOutputStream(endsrc);
dis = new BufferedInputStream(fis);
dos = new BufferedOutputStream(fos);
//定義一個數組儲存位元組資料
byte[] b = new byte[1024];
//定義一個int變數len記錄讀取到的有效個數,如果讀到檔案末尾了,返回-1
int len = 0;
//遍歷讀取資料並將資料寫入指定目的路徑
while((len = dis.read(b)) != -1){
dos.write(b, 0, len);
dos.flush();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(dos != null){
//關閉資源
dos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(dis != null){
//關閉資源
dis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
執行前資料夾截圖
需要被拷貝的資料夾截圖:
拷貝到的目的地址路徑截圖:
執行結束後目的地址的路徑截圖: