1. 程式人生 > 其它 >Java學習筆記(15):複製檔案

Java學習筆記(15):複製檔案

技術標籤:Java學習筆記java

一:複製單級檔案

package 複製檔案;

import java.io.*;

public class 複製單級檔案 {
    public static void main(String[] args) throws IOException{
        //這是要複製的檔案
        File f = new File("D:\\c");
        //獲取要複製的檔案的名字
        String fName = f.getName();
        //目的目錄在TEXT下,名字與要複製的檔案的名字相同
File f2 = new File("TEXT",fName); //如果目的目錄不存在,則建立檔案 if(!f2.exists()){ f2.mkdir(); } //獲取源目錄裡面的File集合並遍歷 File[] list = f.listFiles(); for(File src:list){ //保持名稱相同 String name = src.getName(); File df =
new File(f2,name); copyFile(df,src); } } private static void copyFile(File df, File src) throws IOException { // BufferedReader bf = new BufferedReader(new FileReader(src)); BufferedWriter bw = new BufferedWriter(new FileWriter(df)); // String line =
null; while((line = bf.readLine())!=null){ bw.write(line); bw.newLine(); } // bf.close(); bw.close(); } }

二:複製多級檔案(遞迴)

package 複製檔案;

import java.io.*;


public class 複製多級檔案 {
    public static void main(String[] args) throws IOException {
        File f = new File("D:\\aa");
        File f2 = new File("D:\\a\\");
        copyFolder(f,f2);
    }

    private static void copyFolder(File f, File f2) throws IOException{
        if(f.isDirectory()){
            File f3 = new File(f2,f.getName());

            if(!f3.exists()){
                f3.mkdir();
            }

            File[] list = f.listFiles();

            for(File file:list){
                copyFolder(file,f3);
            }

        }else{
            File newf2 = new File(f2,f.getName());
            copyFile(f,newf2);
        }
    }

    private static void copyFile(File f, File f2) throws IOException{
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(f2));
        byte[] b = new byte[1024];
        int len;
        while((len = bis.read(b))!=-1){
            bos.write(b,0,len);
        }
        bis.close();bos.close();
    }
}