java - 使用Java复制文件会跳过连续两个空格的文件名

标签 java exec whitespace

<分区>

这有点令人困惑。以下批处理片段导致复制这两个文件:

xcopy "C:\Source\Spaces1 [ ].txt" "C:\Target\" /Y
xcopy "C:\Source\Spaces2 [  ].txt" "C:\Target\" /Y

下面使用流的 Java 片段也会导致复制这两个文件:

public static void main(final String args[]) throws IOException
{
    final File source1 = new File("C:\\Source", "Spaces1 [ ].txt");
    final File target1 = new File("C:\\Target", "Spaces1 [ ].txt");
    fileCopy(source1, target1);

    final File source2 = new File("C:\\Source", "Spaces2 [  ].txt");
    final File target2 = new File("C:\\Target", "Spaces2 [  ].txt");
    fileCopy(source2, target2);
}

public static void fileCopy(final File source, final File target) throws IOException
{
    try (InputStream in = new BufferedInputStream(new FileInputStream(source));
            OutputStream out = new BufferedOutputStream(new FileOutputStream(target));)
    {
        final byte[] buf = new byte[4096];
        int len;
        while (0 < (len = in.read(buf)))
        {
            out.write(buf, 0, len);
        }
        out.flush();
    }
}

但是,在此代码段中,其中一个文件未被复制(跳过带有双空格的文件):

public static void main(final String args[]) throws Exception
{
    final Runtime rt = Runtime.getRuntime();
    rt.exec("xcopy \"C:\\Source\\Spaces1 [ ].txt\" \"C:\\Target\\\" /Y").waitFor();

    // This file name has two spaces in a row, and is NOT actually copied
    rt.exec("xcopy \"C:\\Source\\Spaces2 [  ].txt\" \"C:\\Target\\\" /Y").waitFor();
}

这是怎么回事?这将用于从谁知道什么来源复制文件,人们可以在其中输入他们喜欢的任何内容。文件名已清理,但谁来清理连续的两个空格?我在这里缺少什么?

目前使用 Java 8,但 Java 6 和 7 给出相同的结果。

最佳答案

这一切都在 Javadoc 中。

Runtime#exec(String) 委托(delegate)给 Runtime#exec(String,null,null)

exec(String,null,null) 委托(delegate)给 exec(String[] cmdarray,envp,dir)

然后

More precisely, the command string is broken into tokens using a StringTokenizer created by the call new StringTokenizer(command) with no further modification of the character categories. The tokens produced by the tokenizer are then placed in the new string array cmdarray, in the same order.

此时两个空格丢失,当操作系统重新组装命令字符串时变成一个空格。

关于java - 使用Java复制文件会跳过连续两个空格的文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44953109/

相关文章:

java - 使用 Golang 中的类路径和库路径运行 Java 命令

java - 为什么日期从 1970 年 1 月 1 日开始计算?

java - 我可以检测某些手机是否无法播放某些音频文件吗?

java - 如何在java GUI中快速更新图像

unix - 如何使用tcl文件中的sed

c - 如何在 chroot jail 中执行 shell 命令

java - 背包变化算法

css - 在 Windows 上使用多种语言和网络字体时,Chrome 换行文本

diff - svn diff 空白/制表符仅更改

java - 用空格分隔列表项,用选项卡分隔更高级别的指标