2017-07-06 42 views
2

這有點讓人迷惑。在複製這兩個文件下一批片斷結果:用Java複製文件跳過連續兩個空格的文件名

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給出了相同的結果。

+0

我試着用斜槓(不起作用)轉義空格,並試圖用'%20'替換空格(不起作用)。而且,是的,我已經知道我可以使用Robocopy。 –

+0

你有沒有試過先複製雙空間文件,然後單個空間文件,並給出相同的結果呢? –

+0

是的,我確實嘗試過。好的建議,但結果相同。 –

回答

0

這一切都在Javadoc。

Runtime#exec(String)委託給Runtime#exec(String,null,null)

exec(String,null,null)委託給exec(String[] cmdarray,envp,dir)

然後

更確切地說,該命令串被分成使用由呼叫新的StringTokenizer(命令)創建的的StringTokenizer與令牌沒有進一步修改字符類別。令牌生成器生成的令牌隨後以相同的順序放置在新的字符串數組cmdarray中。

這兩個空格在此處丟失,當操作系統重新組裝命令字符串時,兩個空格將會丟失。