How to "Open" and "Save" using java
Asked Answered
M

6

52

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?

Marlenmarlena answered 23/8, 2010 at 13:44 Comment(1)
The question is valid; don't downvote just because someone is not a native English speaker. Instead post a comment how to improve the question.Pimply
T
38

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.

Tonguing answered 23/8, 2010 at 13:46 Comment(0)
C
65

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

Chartography answered 23/8, 2010 at 13:49 Comment(2)
Whatever component you want it to be modal to goes there.Chartography
@Arnold: Or just replace modalToComponent to nullNonanonage
T
38

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.

Tonguing answered 23/8, 2010 at 13:46 Comment(0)
B
3

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

Brownout answered 23/8, 2010 at 13:48 Comment(0)
P
2

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

Pimply answered 23/8, 2010 at 13:47 Comment(0)
A
2

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.

Albinaalbinism answered 23/8, 2010 at 13:47 Comment(0)
I
0

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

Java Desktop application: SWT vs. Swing

Implosion answered 23/8, 2010 at 13:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.