JithPS
JithPS

Reputation: 1217

Writting an image into folder in java project

I am doing a java project in which im reading images from the folder in the project, but I cant write an image file into the same folder I get a exception like resource not found

I could use the image from a folder in project like:

jMenuItem1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imageselection/Images/open.png")));

when I try to write image into same folder like k is BufferedImage

 ImageIO.write( k, "jpg", new File("D:/pass.jpg"));

It works well, but when I write into

ImageIO.write( k, "jpg", new File("/imageselection/Images/open.png"));

it is not working.

"/imageselection/Images" is a folder in my project.

How to solve it?

Upvotes: 1

Views: 1547

Answers (2)

Joop Eggen
Joop Eggen

Reputation: 109547

If you use a getResource URL, the URL not necessarily is on the file system. If you compiled your application to a .jar file (zip format), then it is a file inside the jar zip. So for resources one cannot write.

A feasable solution is (for instance):

  • Make an application data directory;
  • Try first to find the image there as File;
  • Otherwise load the image as resource;
  • Write to the app data dir.

    File appDataDir = new File(System.getProperty("user.home") + "/MyApp");
    appDataDir.mkdirs();
    

Upvotes: 2

Don Chakkappan
Don Chakkappan

Reputation: 7560

ImageIO.write( k, "jpg", new File("./imageselection/Images/open.png"));

will work , you forget to add '.'

Upvotes: 2

Related Questions