Appending the file type to a file in Java using JFileChooser

妖精的绣舞 提交于 2019-12-01 04:42:13

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.

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

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