Take the 2-minute tour ×

I have been tearing my hair out on this and thus I am looks for some help .

I have a loop of code that performs the following

//imports ommitted
public void afterPropertiesSet() throws Exception{

  //building of URL list ommitted  
  // urlMap is a HashMap <String,String> created and populated just prior   

    for ( Object urlVar : urlMap.keySet() ){
    String myURLvar = urlMap.get(urlVar.toString);
    System.out.println ("URL is "+myURLvar );
    BufferedImage imageVar = ImageIO.read(myURLvar);//URL confirmed to be valid even for executions that fail
    String fileName2Save = "filepath"// a valid file path
    System.out.println ("Target path is "+fileName2Save );
    File file2Save = new File (fileName2Save);
    fileName2Save.SetWriteable(true);//set these just to be sure
       ImageIO.write (imageVar,"png",file2save)//error thrown here 
      }catch (Exception e){
     System.out.println("R: "+file2Save.canRead()+" W: "+file2Save.canWrite()+" E:"+file2Save.canExecute()+" Exists: "+file2Save.exists+" is a file"+file2Save.isFile() );

     System.out.println("parent Directory perms");// same as above except on parent directory of destination
      }//end try
     }//end for

This all runs on Windows 7 and JDK 1.6.26 and Netbeans,Tomcat 7.0.14 . The target directory is actually inside my netbeans project directory in a folder for a normal web app ( outside WEB-INF) where I would expect normally to have permission to write files.

When the error occurs I get one of two results for the file a.) All false b.)all true. The Parent directory permission never change all true except for isFile.

The error thrown ( java.IO.error with "access denied" ") does not occur every time ... in fact 60% of the time the loop runs it throws no error. The remaining 40% of the time I get the error on 1 of the 60+ files it writes. Infrequently the same one. The order in which the URLs it starts from changes everytime so the order in which the files are written is variable. The file names have short concise names like "1.png". The images are small..less then 8k.

In order to make sure the permissions are correct I have :

Given "full control" to EVERYONE from the net beans project directory down

Run the JDK,JRE and Netbeans as Administrator

Disabled UAC

Yet the error persists. Google searches for this seem to run the gamut and often read like vodoo. Clearly I ( and Java and Netbeans etc ) should have permission to write a file to the directory .

Anyone have any insight ? This is all ( code and the web server hosting the URL) on a closed system so I can't cut and paste code or stacktrace.

Update: I confirmed the imageURL is valid by doing a println & toString prior to each read. I then confirmed that a.) the web server hosting the target URL returned the image with a http 200 code b.) that the URL returned the image when tested in a web browser. In testing I also put a if () in after the read to confirm that the values was not NULL or empty. I also put in tests for NULL on all the other values . They are always as expected even for a failure .The error always occurs inside the try block. The destination directory is the same every execution. Prior to every execution the directory is empty.

Update 2: Here is one of the stack traces ( in this case perms for file2Save are R: True W:True E: True isFile:True exists:True )

    java.io.FileNotFoundException <fullFilepathhere> (Access is denied)
       at java.io.RandomAccessFile.open(Native Method)
       at java.io.RandomAccessFile.<init>(RandomAccessFile.java:212)
       at javax.imageio.stream.FileImageOutputStream.<init>(FileImageOutputStream.java:53)
       at com.sun.imageio.spi.FileImageOutputStreamSpi.createOutputStreamInstance(FileImageOutputStreamSpi.java:37)
       at javax.imageio.ImageIO.createImageOutputStream(ImageIO.java:393)
       at javax.imageio.ImageIO.write(ImageIO.java:1514)
       at myPackage.myClass.afterPropertiesSet(thisClassexample.java:204)// 204 is the line number of the ImageIO write
share|improve this question
Post your actual code. This isn't valid Java. –  erickson Jul 29 '11 at 1:59
paste the stack trace or error as well . Are you possibly trying to to something that is use by some process. Paste the stack trace. –  Shahzeb Jul 29 '11 at 2:09
If you can write 60% of the time and not the other 30% what happens during the remaining 10% of the time? ok, jokes aside - does the location where you save the image change each time (different folder)? Is ImageIO.read(URL) returning a valid BufferedImage. I don't see a NPE check anywhere.. Please provide more info. –  Drupad Panchal Jul 29 '11 at 2:12
Are you writing to an existing file? There is a file locking issue on Windows if you run it under tomcat or jetty. –  gigadot Jul 29 '11 at 3:07
@stimpy: I lost my mind as well... I have reasons to believe that the issue is raised by the ImageIO.write(...) function. Saving the image in an old school fashion is a quick fix to the issue. In my case I decided not to use BufferedImage at all. If you cannot move away from BufferdImage there should still be a way to convert it to a byte[] and save it piece by piece anyway. –  Gevorg Aug 21 '11 at 0:21
show 10 more comments

2 Answers

up vote 1 down vote accepted

This may not answer your problem since there can be many other possibilties to your limited information.

One common possibilty for not being able to write a file in web application is the file locking issue on Windows if the following four conditions are met simultaneously:

  1. the target file exists under web root, e.g. WEB-INF folder and
  2. the target file is served by the default servlet and
  3. the target file has been requested at least once by client and
  4. you are running under Windows

If you are trying to replace such a file that meets all of the four conditions, you will not be able to because some servlet containers such as tomcat and jetty will buffer the static contents and lock the files so you are unable to replace or change them.

If your web application has exactly this problem, you should not use the default servlet to serve the file contents. The default servlet is desigend to serve the static content which you do not want to change, e.g. css files, javascript files, background images, etc.

There is a trick to solve the file locking issue on Windows for jetty by disabling the NIO http://docs.codehaus.org/display/JETTY/Files+locked+on+Windows

The trick is useful for development process, e.g. you want to edit the css file and see the change without restarting your web application, but it is not recommended for production mode. If your web application relies on this trick in the production process, then you should seriously consider redesign your codes.

share|improve this answer
Nice. I did not know this however, I think Condition 3 is not true in this case ( no clients connected to this server during testing) also condition 2 is also likely not true ( App is named servlet that is not the default ). But thanks for a good answer. –  stimpy Jul 29 '11 at 11:57
This turns out to be the case however the only real condition is " Tomcat running on windows" . Running the same code on Linux produced no errors . Turning on tomcat's anti-resource locking reduced the frequency of the problem( which is not really a solution ) . Ultimately the only way to avoid this problem is to NOT run under windows ( Windows 7 and Server 2008 tested ) –  stimpy Aug 16 '11 at 17:22
I had the same issue even if the 4 conditions didn't hold true in my case.. –  Gevorg Aug 21 '11 at 22:37
Gevorg did you have the problem with tomcat NOT running under windows ? In my case this proved to be the "solution ". –  stimpy Aug 21 '11 at 23:21
My program is a scheduled standalone application. I did have the issue running it in windows 7 64bit. I haven't tried it on linux and I probably won't cause I completely changed my approach before figuring out the workaround described in my other answer. –  Gevorg Aug 22 '11 at 14:49
add comment

I cannot tell you what's going on or why... I have a feeling that it's something dependent on the way ImageIO tries to save the image. What you could do is saving the BufferedImage by leveraging the ByteArrayOutputStream as described below:

BufferedImage bufferedImage = ImageIO.read(new File("sample_image.gif"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write( bufferedImage, "gif", baos );

baos.flush(); //Is this necessary??
byte[] resultImageAsRawBytes = baos.toByteArray();
baos.close(); //Not sure how important this is...

OutputStream out = new FileOutputStream("myImageFile.gif");

I'm not really familiar with the ByteArrayOutputStream, but I guess its reset() function could be handy when dealing with saving multiple files. You could also try using its writeTo(OutputStream out) if you prefer. Documentation here.

Let me know how it goes...

share|improve this answer
I will give this a try and see if it changes things . Thanks for the input –  stimpy Aug 21 '11 at 23:22
add comment

Your Answer


