Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save file using JFileChooser?

I have a method in my application called "Save as" which Saves the image of my application on computer my into a file. I used the JFileChooser to let the users choose their desired location for saving the file. The problem is unless user explicitly types in the file format, it saves the file with no extension. How can I have formats like jpg, png in the File Type drop down menu.

and, how can i get extension from the File Type drop menu for saving my image file.

 ImageIO.write(image,extension,file);
like image 299
Lokesh Kumar Avatar asked Mar 27 '10 21:03

Lokesh Kumar


People also ask

How do I find my JFileChooser file name?

JFileChooser has a method, getSelectedFile(). Which is a File. If you open the dialog with showSaveDialog() you should be able to get the File from that (file. getName()).

How do I save a file in a directory in Java?

Try something like this: File file = new File("/some/absolute/path/myfile. ext"); OutputStream out = new FileOutputStream(file); // Write your data out. close();


1 Answers

Finally, I solved my own problem:

JFileChooser fc = new JFileChooser("C:/");
fc.addChoosableFileFilter(new JPGSaveFilter());
fc.addChoosableFileFilter(new JPEGSaveFilter());
fc.addChoosableFileFilter(new PNGSaveFilter());
fc.addChoosableFileFilter(new GIFSaveFilter());
fc.addChoosableFileFilter(new BMPSaveFilter());
fc.addChoosableFileFilter(new WBMPSaveFilter()); 

int retrieval = fc.showSaveDialog(null);

if (retrieval == JFileChooser.APPROVE_OPTION) {
  String ext = "";

  String extension = fc.getFileFilter().getDescription();

  if (extension.equals("*.jpg,*.JPG")) {
    ext = ".jpg";
  } else if (extension.equals("*.png,*.PNG")) {
    ext = ".png";
  } else if (extension.equals("*.gif,*.GIF")) {
    ext = ".gif";
  } else if (extension.equals("*.wbmp,*.WBMP")) {
    ext = ".wbmp";
  } else if (extension.equals("*.jpeg,*.JPEG")) {
    ext = ".jpeg";
  } else if (extension.equals("*.bmp,*.BMP")) {
    ext = ".bmp";
  }
}

Example Filter:

package example

import java.io.File;
import javax.swing.filechooser.FileFilter;

class JPGSaveFilter extends FileFilter {
  @Override
  public boolean accept(File f) {
    if (f.isDirectory()) {
      return false;
    }

    String s = f.getName().toLowerCase();

    return s.endsWith(".jpg");
  }

  @Override
  public String getDescription() {
    return "*.jpg,*.JPG";
  }
}
like image 112
Lokesh Kumar Avatar answered Oct 08 '22 16:10

Lokesh Kumar