How to "Open" and "Save" using java

JavaSwingJfilechooser

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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.

Solution 3 - Java

Maybe you could take a look at JFileChooser, which allow you to use native dialogs in one line of code.

Solution 4 - Java

You can find an introduction to file dialogs in the Java Tutorials. Java2s also has some example code.

Solution 5 - Java

First off, you'll want to go through Oracle's tutorial to learn how to do basic I/O in Java.

After that, you will want to look at the tutorial on how to use a file chooser.

Solution 6 - Java

You may also want to consider the possibility of using SWT (another Java GUI library). Pros and cons of each are listed at:

https://stackoverflow.com/questions/2306190/java-desktop-application-swt-vs-swing/2306275#2306275

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHuuhaaceceView Question on Stackoverflow
Solution 1 - JavaErick RobertsonView Answer on Stackoverflow
Solution 2 - JavaMike ClarkView Answer on Stackoverflow
Solution 3 - JavaRiduidelView Answer on Stackoverflow
Solution 4 - JavaAaron DigullaView Answer on Stackoverflow
Solution 5 - JavadbyrneView Answer on Stackoverflow
Solution 6 - JavaSinjoView Answer on Stackoverflow