Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending the file type to a file in Java using JFileChooser

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.

like image 523
Kingteeb Avatar asked May 06 '12 14:05

Kingteeb


2 Answers

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.

like image 130
Jeffrey Avatar answered Nov 09 '22 06:11

Jeffrey


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" ); 
like image 44
Christian Garbin Avatar answered Nov 09 '22 06:11

Christian Garbin