简体   繁体   中英

FileNotFoundException on FileOutputStream in spite of mkdirs() and createNewFile()

I have a bean that download emails from SMTP server. 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. If can help, I use NetBeans with GlassFish and the tests are made in debug in local machine.

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.

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.
  • you should check the return value of your call to createNewFile() .

The simplest way to make it work is by replacing your line with:

f.getParentFile().mkdirs();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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