简体   繁体   English

尽管有mkdirs()和createNewFile(),但FileOutputStream上的FileNotFoundException

[英]FileNotFoundException on FileOutputStream in spite of mkdirs() and createNewFile()

I have a bean that download emails from SMTP server. 我有一个可从SMTP服务器下载电子邮件的bean。 After read emails it saves attachments on the server. 阅读电子邮件后,它将附件保存在服务器上。 To read attachment I use this code: 要阅读附件,请使用以下代码:

File f = new File("\\attachments\\" + attachment.getFileName());
f.mkdirs();
f.createNewFile();
FileOutputStream fos = new FileOutputStream(f);
fos.write(bytes);
fos.close();

I got a FileNotFoundException on FileOutputStream creating and I can't understand why. 我在创建FileOutputStream时遇到FileNotFoundException,但我不明白为什么。 If can help, I use NetBeans with GlassFish and the tests are made in debug in local machine. 如果可以帮助,我将NetBeans与GlassFish一起使用,并且测试是在本地计算机的调试中进行的。

When you do 当你做

f.mkdirs();

You are creating a directory with the name of your file (that is, you create not only the directory "attachments", you also create a subdirectory with the name of your attachment filename). 您正在使用文件名创建目录(即,您不仅创建目录“附件”,还创建了具有附件文件名的子目录)。 Then 然后

f.createNewFile();

does not do anything since the file already exist (in the form of a directory you just created). 由于文件已经存在(以您刚创建的目录形式),因此不会执行任何操作。 It returns false to tell you that the file already exists. 它返回false告诉您该文件已经存在。

Then this fails: 然后这失败了:

FileOutputStream fos = new FileOutputStream(f);

You are trying to open an output stream on a directory. 您正在尝试在目录上打开输出流。 The system doesn't allow you to write in a directory, so it fails. 系统不允许您在目录中写入,因此失败。

The bottom line is: 底线是:

  • mkdirs() doesn't do what you think it does. mkdirs()不会执行您认为的操作。
  • you should check the return value of your call to createNewFile() . 您应该检查对createNewFile()调用的返回值。

The simplest way to make it work is by replacing your line with: 使它工作的最简单方法是将您的行替换为:

f.getParentFile().mkdirs();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM