无效的文件路径异常



我的应用程序引发了异常-java.io.filenotfoundexception:无效的文件路径。不知道为什么。我已经阅读了有关主题的问题和答案,但没人能帮助我。

这是代码:

    String userhome = System.getProperty("user.home");
    String filename = null;
    File rdp = null;
    for (int item = 0; item < darab; item++) {
        filename = toValidFileName(ProgramList.get(item).getP_name());
        filename += ".rdp";
        rdp = new File(userhome, filename);
        try {
            JFrame panel;
            panel = new JFrame();
            panel.setSize(400, 10);
            panel.setLocation(300, 400);
            panel.setTitle("Saving " + rdp.getAbsolutePath());
            try (FileOutputStream fstr = new FileOutputStream(rdp)) {
                panel.setVisible(true);
                char c;
                for (int j = 0; j < 2336; j++) {
                    c = ProgramList.get(item).p_body.charAt(j);
                    fstr.write(c);
                }
                fstr.flush();
                fstr.close();
                panel.setVisible(false);
            }
        } catch (IOException ioe) {
            JOptionPane.showMessageDialog(this,
                    ioe.getMessage(), "Save rdp file", JOptionPane.ERROR_MESSAGE);
            System.err.println(ioe.getMessage() + " : "+ rdp.getAbsoluteFile());
        }
    }

和结果:无效的文件路径:C: Users Lipi cosmicld.rdp

tovalidfilename()被删除(Korg Radias)程序名称中的禁止字符以创建有效的文件名。

我没有发现我的错:(目标目录不仅读取,用户具有必要的特权。当我在行之后查看file.canwrite()时: rdp = new File(userHome,fileName);总是错误的。我做错了什么?谢谢!

尝试使用filewriter。您的尝试将看起来像这样:

try {
     File dir = new File("C:/Users//" + userhome + "/Documents"); //customize this however
     FileWriter fstr = new FileWriter(new File(dir, rdp));
          for (int j = 0; j < 2336; j++) {
                c = ProgramList.get(item).p_body.charAt(j);
                fstr.write(c);
                        }
            fw.close(); 
        }

另外,请尝试坚持使用Java变量命名约定。UserHome应该是用户屋等。只是一个小事:)

在该行中生成了问题:

filename = toValidFileName(ProgramList.get(item).getP_name());

使用getp_name()结果,因为有时它具有(char)0个字符...

代码被重写 ->(char)0字符已更改为对象中的20个字符,以这种方式,一切都在工作。

无论如何,tovalidfilename代码:

public static String toValidFileName(String input) {
    return input.replaceAll("[:\\/*"?|<>']", "_");
}

谢谢大家的帮助!有一些有用的建议,尤其是Arkady和VGR的建议!

最新更新