views:

17468

answers:

4

Hey everyone,

I was wondering if there was some kind of J tool in the java swing library that opens up a file browser window and allows a user to choose a file. then the ouput of the file would be the absolute path of the chosen file.

Thanks in advance,

Tomek

+9  A: 

You can use the JFileChooser class, check this example.

CMS
If you don't need all the flexibility of JFileChooser, you should use java.awt.FileDialog instead. Your OS X users will thank you. FileDialog uses a native file chooser window, while JFileChooser is a swing component, and lacks keyboard shortcuts and other niceties.
Sam Barnum
+4  A: 

thanks for the heads up. I ended up using this quick piece of code that did exactly what i needed.

            final JFileChooser fc = new JFileChooser();
            fc.showOpenDialog(this);

            try {
                // Open an input stream
                Scanner reader = new Scanner(fc.getSelectedFile());
            }
Tomek
+4  A: 

The following example creates a file chooser and displays it as first an open-file dialog and then as a save-file dialog:

String filename = File.separator+"tmp";
JFileChooser fc = new JFileChooser(new File(filename));

// Show open dialog; this method does not return until the dialog is closed
fc.showOpenDialog(frame);
File selFile = fc.getSelectedFile();

// Show save dialog; this method does not return until the dialog is closed
fc.showSaveDialog(frame);
selFile = fc.getSelectedFile();

Here is a more elaborate example that creates two buttons that create and show file chooser dialogs.

// This action creates and shows a modal open-file dialog.
public class OpenFileAction extends AbstractAction {
    JFrame frame;
    JFileChooser chooser;

    OpenFileAction(JFrame frame, JFileChooser chooser) {
        super("Open...");
        this.chooser = chooser;
        this.frame = frame;
    }

    public void actionPerformed(ActionEvent evt) {
        // Show dialog; this method does not return until dialog is closed
        chooser.showOpenDialog(frame);

        // Get the selected file
        File file = chooser.getSelectedFile();
    }
};

// This action creates and shows a modal save-file dialog.
public class SaveFileAction extends AbstractAction {
    JFileChooser chooser;
    JFrame frame;

    SaveFileAction(JFrame frame, JFileChooser chooser) {
        super("Save As...");
        this.chooser = chooser;
        this.frame = frame;
    }

    public void actionPerformed(ActionEvent evt) {
        // Show dialog; this method does not return until dialog is closed
        chooser.showSaveDialog(frame);

        // Get the selected file
        File file = chooser.getSelectedFile();
    }
};
iberck
A: 

In WebStart and the new 6u10 PlugIn you can use the FileOpenService, even without security permissions. For obvious reasons, you only get the file contents, not the file path.

Tom Hawtin - tackline