2010-04-13

利用 Java 複製與删除檔案及目錄 (Use Java to copy and delete a file or a directory)

import java.io.File;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Arrays;

public static void copy(File source, File destination) throws IOException, FileNotFoundException{
    if (source. exists() && !source.equals(destination)){
        if (source.isFile()){
            FileInputStream fis = new FileInputStream(source);
            FileOutputStream fos = new FileOutputStream(destination);
            byte[] buffer = new byte[1024];
            for (int length; (length = fis.read(buffer)) > 0; fos.write(buffer, 0, length));
            fos.close();
            fis.close();
        } else if (source.isDirectory()){
            if (!destination.exists()){
                destination.mkdir();
            }
            File[] files = source.listFiles();
            for (File file : files){
                copy(file, new File(destination, file.getName()));
            }
        }
    }
}

public static void delete(File file) throws IOException, FileNotFoundException{
    if (file.exists()){
        if (file.isDirectory()){
            File[] files = file.listFiles();
            for (File f : files){
                delete(f);
            }
        }
        file.delete();
    }
}

沒有留言 :

張貼留言