Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "Open" and "Save" using java

I want to make an "Open" and "Save" dialog in java. An example of what I want is in the images below:

Open:

Open file dialog

Save:

Save file dialog

How would I go about doing this?

like image 685
Huuhaacece Avatar asked Aug 23 '10 13:08

Huuhaacece


2 Answers

You want to use a JFileChooser object. It will open and be modal, and block in the thread that opened it until you choose a file.

Open:

 JFileChooser fileChooser = new JFileChooser(); if (fileChooser.showOpenDialog(modalToComponent) == JFileChooser.APPROVE_OPTION) {   File file = fileChooser.getSelectedFile();   // load from file } 

Save:

 JFileChooser fileChooser = new JFileChooser(); if (fileChooser.showSaveDialog(modalToComponent) == JFileChooser.APPROVE_OPTION) {   File file = fileChooser.getSelectedFile();   // save to file } 

There are more options you can set to set the file name extension filter, or the current directory. See the API for the javax.swing.JFileChooser for details. There is also a page for "How to Use File Choosers" on Oracle's site:

http://download.oracle.com/javase/tutorial/uiswing/components/filechooser.html

like image 151
Erick Robertson Avatar answered Sep 22 '22 23:09

Erick Robertson


I would suggest looking into javax.swing.JFileChooser

Here is a site with some examples in using as both 'Open' and 'Save'. http://www.java2s.com/Code/Java/Swing-JFC/DemonstrationofFiledialogboxes.htm

This will be much less work than implementing for yourself.

like image 25
Mike Clark Avatar answered Sep 22 '22 23:09

Mike Clark