0

I am retrieving an image file with the following lines of code...

How do I make sure it ends up in the project file location?

public void run() {
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setFileFilter(new FileNameExtensionFilter("Images", "jpg", "png"));
    while (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
        try {
            File f = fileChooser.getSelectedFile();  
            BufferedImage thisImage = ImageIO.read(f);
        }
    }
}

I assume I am supposed to use ImageIO.write() in some way?? Nothing I have dont works.

Two things I've tried:

Files.copy(f.toPath(), new File(System.getProperty("user.dir")).toPath(), StandardCopyOption.REPLACE_EXISTING);

ImageIO.write(thisImage, "png", f);

  • What do you mean by "the project file location"? Do you mean where the code is executing from? – Gregg Nov 29 '22 at 20:12
  • I’m not sure what you’re trying to accomplish. If you want to make an image viewer, you don’t need to copy the files. – VGR Nov 29 '22 at 21:47

1 Answers1

0

System.getProperty("user.dir") will return the path for the current working dir. I'm assuming that's what you mean. Then it's just using what you suggested to write the file out.

var workingDir = System.getProperty("user.dir");
var outputfile = new File(workingDir + "/saved.png");
ImageIO.write(yourBufferedImage, "png", outputfile);

Something like that anyway.

Gregg
  • 34,973
  • 19
  • 109
  • 214
  • all I am looking for is a way to use a JFileChooser to retrieve a file from my PC, and programmatically save it as a file inside the source folder of a java project. – Kai Kishpaugh Nov 30 '22 at 04:28