如何从 JFileChooser 将图像文件保存到 java 项目文件位置?

How do I save image file into java project file location from JFileChooser?

提问人:Kai Kishpaugh 提问时间:11/30/2022 更新时间:11/30/2022 访问量:13

问:

我正在使用以下代码行检索图像文件...

如何确保它最终位于项目文件位置?

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);
        }
    }
}

我想我应该以某种方式使用 ImageIO.write() ??我所拥有的任何东西都不起作用。

我尝试过两件事:

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

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

java 保存 文件位置

评论

0赞 Gregg 11/30/2022
“项目文件位置”是什么意思?你的意思是代码从哪里执行的吗?
0赞 VGR 11/30/2022
我不确定你想完成什么。如果要制作图像查看器,则无需复制文件。

答:

0赞 Gregg 11/30/2022 #1

System.getProperty("user.dir")将返回当前工作目录的路径。我假设这就是你的意思。然后它只是使用您建议的内容将文件写出来。

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

反正就是这样。

评论

0赞 Kai Kishpaugh 11/30/2022
我正在寻找的只是一种使用 JFileChooser 从我的 PC 中检索文件的方法,并以编程方式将其保存为 java 项目的源文件夹中的文件。