java FileChannel File 临时文件 互相拷贝

class SwapFilesUsingFileChannel {
    public static void main(String[] args) {
        File a = new File("a.mp3"),
             b = new File("b.mp3");
        try {
            File temp = File.createTempFile("你的前辍", "你的后辍");
            temp.deleteOnExit();
            copyFile(a, temp);
            copyFile(b, a);
            copyFile(temp, b);
            System.out.println("OK");
        } catch (IOException e) {
            System.err.println("Failed: " + e.getMessage());
        }
    }

    static void copyFile(File source, File target) throws IOException {
        FileChannel sourceChannel = new FileInputStream(source).getChannel(),
                    targetChannel = new FileOutputStream(target).getChannel();
        sourceChannel.transferTo(0, sourceChannel.size(), targetChannel);
        sourceChannel.close();
        targetChannel.close();
    }
}

你可能感兴趣的:(java FileChannel File 临时文件 互相拷贝)