拷贝文件的几种方法

public class CopyFile1 {
    private static void copyFileUsingFileStreams(File source, File dest)
            throws IOException {
        InputStream input = null;
        OutputStream output = null;
        try {
            input = new FileInputStream(source);
            output = new FileOutputStream(dest);
            byte[] buf = new byte[1024];
            int bytesRead;
            while ((bytesRead = input.read(buf)) > 0) {
                output.write(buf, 0, bytesRead);
            }
        } finally {
            input.close();
            output.close();
        }
    }

    private static void copyFileUsingFileChannels(File source, File dest) throws IOException {
        FileChannel inputChannel = null;
        FileChannel outputChannel = null;
        try {
            inputChannel = new FileInputStream(source).getChannel();
            outputChannel = new FileOutputStream(dest).getChannel();
            outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
        } finally {
            inputChannel.close();
            outputChannel.close();
        }
    }

    private static void copyFileUsingApacheCommonsIO(File source, File dest)
            throws IOException {
       // FileUtils.copyFile(source, dest);
    }

    private static void copyFileUsingJava7Files(File source, File dest)
            throws IOException {
        Files.copy(source.toPath(), dest.toPath());
    }

    public static void main(String[] args) throws IOException {
        //copyFileUsingFileStreams(new File("C:\\Users\\w_wangsh\\Desktop\\a\\20210625\\CashReport.dll"),new File("C:\\Users\\w_wangsh\\Desktop\\a\\20210625\\CashReport2.dll"));
        //copyFileUsingFileChannels(new File("C:\\Users\\w_wangsh\\Desktop\\a\\20210625\\CashReport.dll"),new File("C:\\Users\\w_wangsh\\Desktop\\a\\20210625\\CashReport2.dll"));
        copyFileUsingJava7Files(new File("C:\\Users\\w_wangsh\\Desktop\\a\\20210625\\CashReport.dll"),new File("C:\\Users\\w_wangsh\\Desktop\\a\\20210625\\CashReport2.dll"));
    }

 

上一篇:Android IntentService的使用和源码分析


下一篇:Ubuntu下matlab创建图标