Reputation: 919
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.
Upvotes: 1
Views: 1401
Reputation: 15523
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.createNewFile()
.The simplest way to make it work is by replacing your line with:
f.getParentFile().mkdirs();
Upvotes: 6