-1

我收到 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);
                    }       
            }

谁能明白为什么会这样?谢谢。

4

1 回答 1

1

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

PS也许尝试使用trim()文件名。

于 2013-02-03T05:26:36.537 回答