Java IOException,文件路径奇怪

时间:2013-02-03 05:12:49

标签: java

我得到了 java.io.IOException:文件名,目录名或卷标语法不正确 我不明白为什么。

如果我直接使用字符串尝试我的代码,它可以工作(文件夹存在,权限正常等) 当我尝试从数组构建字符串时,它失败,上面有例外。 这是代码,我试过的注释行失败了,什么与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);
                    }       
            }

有人能看出为什么会这样吗? 感谢。

1 个答案:

答案 0 :(得分:1)

尝试File targetFile = new File(dlDirectory, filesToRetrieve[i]);

P.S。 也许可以使用trim()文件名。