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.
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);
}
来源:https://stackoverflow.com/questions/10471396/appending-the-file-type-to-a-file-in-java-using-jfilechooser