【问题标题】:Having trouble copying directory from NFS mount in Java在 Java 中从 NFS 挂载复制目录时遇到问题
【发布时间】:2015-06-04 07:50:02
【问题描述】:

我一直在尝试将目录从 NFS 挂载递归复制到 Java 中的本地文件系统。我首先尝试在 Apache Utils 中使用 FileUtils。遗憾的是,它没有递归复制(遍历子目录等),所以我不得不回到绘图板上。我听说其中一些操作在跨设备时是“挑剔的”。然后有人建议我尝试使用 linux 命令,所以我尝试这样做:

Process process = new ProcessBuilder()
                    .command("cp -R " + source.getAbsolutePath() + " " + dest.getAbsolutePath())
                    .start();

process.waitFor();

这可悲地引发了“没有这样的文件或目录”的响应,我在那里进行了一些调试并再次尝试。即使我得到“没有这样的文件或目录”,我的调试表明源目录和目标目录都存在,以及在手动检查它们是否存在之后。

【问题讨论】:

  • 如果任一路径有空格,您可能会遇到问题。虽然这样做有点...... icky,但您可以在每个路径参数周围添加引号。我可以看到不会导致此类文件或目录错误。或者,转义空格和其他特殊字符。不过,我会找到比使用命令更好的方法。
  • 目录或文件中没有空格。

标签: java linux nfs


【解决方案1】:

好的,所以我决定编写自己的实现,奇怪的是它确实有效。可悲的是,我几乎不知道为什么这对 FileUtils 有效。这是我写的:

private void copy(File source, File destination) throws IOException {
    if (source.isDirectory()) {
        if (!destination.exists()) {
            destination.mkdir();
        }

        if (destination.isFile()) {
            destination.delete();
            destination.mkdir();
        }

        for (File src : source.listFiles()) {
            File dest = new File(destination, src.getName());

            copy(src, dest);
        }
    } else {
        destination.createNewFile();

        FileInputStream input = new FileInputStream(source);
        FileOutputStream out = new FileOutputStream(destination);
        byte[] buffer = new byte[2048];
        int l;

        while ((l = input.read(buffer)) > 0) {
            out.write(buffer, 0, l);
        }

        input.close();
        out.close();
    }
}

【讨论】:

    猜你喜欢
    • 2010-09-07
    • 2017-08-06
    • 2020-08-19
    • 2019-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-25
    相关资源
    最近更新 更多