java FileChannel File 临时文件 互相拷贝

来源:互联网 发布:数据库sql语句面试题 编辑:程序博客网 时间:2024/06/05 03:43
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();    }}

原创粉丝点击