This question already has answers here:
Runtime.exec on argument containing multiple spaces
                                
                                    (8个答案)
                                
                        
                                2年前关闭。
            
                    
这有点令人困惑。以下批处理代码片段将复制两个文件:

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)代表Runtime#exec(String,null,null)

exec(String,null,null)代表exec(String[] cmdarray,envp,dir)

然后


  更准确地说,使用调用新StringTokenizer(command)创建的StringTokenizer将命令字符串分解为令牌,而无需进一步修改字符类别。然后以相同的顺序将令牌生成器生成的令牌放置在新的字符串数组cmdarray中。


此时,这两个空格将丢失,并在操作系统重新组合命令字符串时成为一个空格。

09-26 21:01
查看更多