2013-02-03 45 views
-1

我得到 java.io.IOException:文件名,目錄名或卷標語法不正確 我看不到爲什麼。Java IOException,文件路徑奇怪

如果我直接用字符串嘗試我的代碼,它可以工作(文件夾存在,權限ok等) 當我嘗試從數組中構建字符串時,它失敗,出現上述異常。 下面的代碼,與我已經試過了失敗,什麼工程,以及中的println輸出就是註釋行:

  // ////////////////////////////////////////////////////////////////// 
      // Create a file chooser and select a directory 
      JFileChooser fc = new JFileChooser(); 
      fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); 
      fc.setAcceptAllFileFilterUsed(false); 

      int rVal = fc.showOpenDialog(MyApp.this); 

      if (rVal == JFileChooser.APPROVE_OPTION) { 
       dlDirectory = fc.getSelectedFile().toString() + "\\"; 
       System.out.println("Selected Directory: " + dlDirectory); 
      } else { 
       System.out.println("No Selection"); 
      } 

      ... 
      ...(I create a string array of file names here) 
      ... 

      for (int i = 0; i < filesToRetrieve.length; i++) { 

        //put together the directory and file name 
        String dlFileName = (dlDirectory + filesToRetrieve[i]); 
        try { 
           System.out.println(dlDirectory); // output: C:\Users\michael\Documents\tmp\ (as expected) 
           System.out.println(filesToRetrieve[i]); // output: nameoffile.txt (as expected) 
           System.out.println(dlFileName); // output: C:\Users\michael\Documents\tmp\nameoffile.txt (as expected) 

           File myFile = new File(dlFileName); //<--this does not work -- java.io.IOException: The filename, directory name, or volume label syntax is incorrect 
           //File myFile = new File(dlDirectory + filesToRetrieve[i]); //<--this does not work either 

           //File myFile = new File(dlDirectory + "nameoffile.txt"); // <--this does work !?!? 

           if(!myFile.exists()) { 
            System.out.println("file does not exist"); 
            myFile.createNewFile(); 
           } 
        } catch (Exception e) { 
         System.err 
           .println("failed"); 
         System.err.println(e); 
        }  
      } 

有人能看到爲什麼會這樣? 謝謝。

+0

不應該在目錄和filesToRetrieve之間使用\\而不是單個\? – vikiiii

+0

你應該使用'\\\'而不是'\\' – Mob

+0

@Mob,是的,dlFileName是dl目錄中的文件choser和+ \\ + filename,它只是用\ –

回答

1

嘗試File targetFile = new File(dlDirectory, filesToRetrieve[i]);

P.S. 也許試試trim()文件名。

+0

這可能會更好地適合作爲評論,直到它可以驗證爲工作解決方案,恕我直言,但是,我喜歡它 – MadProgrammer

+0

爲什麼它沒有嘗試我試過了我的MAC作者可以嘗試在他的Windows :) –

+0

恕我直言,這是一個偉大的「建議」 – MadProgrammer