java - Java 中的 move/复制文件操作

标签 java file copy move

是否有标准的 Java 库来处理常见的文件操作,例如 move/复制文件/文件夹?

最佳答案

以下是使用 java.nio 操作的方法:

public static void copyFile(File sourceFile, File destFile) throws IOException {
    if(!destFile.exists()) {
        destFile.createNewFile();
    }

    FileChannel source = null;
    FileChannel destination = null;
    try {
        source = new FileInputStream(sourceFile).getChannel();
        destination = new FileOutputStream(destFile).getChannel();

        // previous code: destination.transferFrom(source, 0, source.size());
        // to avoid infinite loops, should be:
        long count = 0;
        long size = source.size();              
        while((count += destination.transferFrom(source, count, size-count))<size);
    }
    finally {
        if(source != null) {
            source.close();
        }
        if(destination != null) {
            destination.close();
        }
    }
}

关于java - Java 中的 move/复制文件操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/300559/

相关文章:

java - 在哪里可以下载 Java 的 rt.jar?

android - 如何使用Flutter App读取Android 10设备文件

c# - 是否可以将面板的内容复制到另一个面板

java - junit 没有任何模拟框架

java - 通过在 Java DatagramSocket 中禁用 SO_RCVBUF 来读取最新的 UDP 数据包?

java - 有人有一个好的 java BitBuffer 吗?

c++ - Getline 函数不解析 CSV 文件中的行尾

c# - 多线程和 C# 异常。文件正在被另一个进程使用

c - 使用C查找文件权限

sql - PostgreSQL `COPY TO` 命令是否(或可以)保证特定的行顺序?