Appending the file type to a file in Java using JFileChooser

一曲冷凌霜 提交于 2019-12-01 02:43:47

问题


I'm trying to save an image using a JFileChooser. I only want the user to be able to save the image as a jpg. However if they don't type .jpg it wont be saved as an image. Is it possible to somehow append ".jpg" to the end of the file?

File file = chooser.getSelectedFile() + ".jpg";  

Doesn't work as I'm adding a string to a file.


回答1:


Why not convert the File to a String and create a new File when you're done?

File f = chooser.getSelectedFile();
String filePath = f.getAbsolutePath();
if(!filePath.endsWith(".jpg")) {
    f = new File(filePath + ".jpg");
}

Remember, you don't need to add the .jpg if it's already there.




回答2:


It works if you do in two steps: add extension to selected file, then create File object with the extension appended to it.

String withExtension = chooser.getSelectedFile().getAbsolutePath() + ".jpg";
File file = new File( withExtension )

Implied in your question, but just to cover all bases: need to check if the extension isn't already there first, e.g.:

String withExtension = chooser.getSelectedFile().getAbsolutePath();
if( !withExtension.toLowerCase().endsWith( ".jpg" ) )
   withExtension += ".jpg";

[You may want to add ".jpeg" to the if above - it's a valid extension for JPEG files]

The code below may or may not work. File has a toString() that will allow it to compile, but I'd rather use the method above, where I can control the exact path name I'm getting. The toString() documentation for the File object is a bit unclear to me on what exactly it returns. In cases like this one, I prefer to call a function that I know returns what I need for sure.

File file = new File( chooser.getSelectedFile() + ".jpg" ); 



回答3:


The best approach would be to check for an acceptable entry. If one isn't found replace the file exention instead of writing on top of it.

File f = chooser.getSelectedFile().getAbsolutePath();
String path = f.getAbsolutePath();
if (!path.matches(".*\\.(jpg|jpeg)")) {
    // If the extension isn't there. We need to replace it
    path = path.substring(0, path.lastIndexOf(".") + 1).concat("jpg");
    f = new File(path);
}


来源:https://stackoverflow.com/questions/10471396/appending-the-file-type-to-a-file-in-java-using-jfilechooser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!