IO流-拷貝目錄

IO流-拷貝目錄

使用:
FileInputStream
FileOutputStream
File
遞歸

直接上代碼:思路請看註釋,有大神幫助改進最好,謝謝

import java.io.*;

/*
拷貝目錄
 */
public class Copy03 {
    public static void main(String[] args) {
        //源目標
        File file = new File("E:\\風景");
        //拷貝目標
        File file1 = new File("D:\\");

        copyDir(file,file1);
    }

    /**
     * 拷貝目錄方法
     * @param file 拷貝源
     * @param file1 拷貝目標
     */
    private static void copyDir(File file, File file1) {
        if (file.isFile()){
            FileInputStream fis = null;
            FileOutputStream fos = null;

            try {

                //讀這個文件
                fis = new FileInputStream(file);

                //先獲取源路徑的相對路徑
                String strFile = file.getAbsolutePath();

                //目標路徑:拷貝目標路徑 + 源路徑(截取掉盤符)後面的路徑。
                String strNew = (file1.getAbsolutePath().endsWith("\\") ? file1.getAbsolutePath():file1.getAbsolutePath() + "\\")+ strFile.substring(3);

                //寫到這個文件中
                fos = new FileOutputStream(strNew);

                //一邊讀一邊寫
                byte[] bytes = new byte[1024 * 1024]; //一次複製1MB
                int ioo = 0;
                while ((ioo = fis.read(bytes)) != -1){
                    fos.write(bytes,0,ioo);
                }

                //刷新
                fos.flush();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            //如果是一個文件的話,遞歸結束
            return;
        }

        //獲取源下的子目錄
        File[] file2 = file.listFiles();
        for(File file3 : file2){
            //獲取所有文件的(包括目錄和文件)絕對路徑
            //System.out.println(file3.getAbsolutePath());
            //如果是一個目錄
            if(file3.isDirectory()){
                //新建對應的目錄
                String str = file3.getAbsolutePath();//獲取源目錄

                //獲取目標目錄
                //判斷是否是以斜槓(\)結尾
                String strSub = (file1.getAbsolutePath().endsWith("\\") ? file1.getAbsolutePath():file1.getAbsolutePath() + "\\") + str.substring(3);

                //新建一個File對象
                File neWFile = new File(strSub);

                //判斷目錄是否存在,如果不存在就新建多重目錄
                if(!neWFile.exists()){
                    neWFile.mkdirs();
                }
            }
            //遞歸調用
            copyDir(file3,file1);
        }
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章