Search code examples
javajfilechooserfile-type

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.


Solution

  • 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.