James
James

Reputation: 113

Java select a file location

I'm not sure if this is even possible as I can't find anything about it after quite a few Google searches.

What I would like to do is on event open up a file dialog box and allow the user to select a folder and then store that folders full directory in a string. So if a user selected a folder in C:\Windows\Example the directory would be stored in String fileDir = C:\Windows\Example;

Does this make sense? I hope so as I'm struggeling to find the answer. I do apperciate the help, thanks in advance for looking and more thanks if you help me :)

Upvotes: 4

Views: 15559

Answers (2)

Joseph Gordon
Joseph Gordon

Reputation: 2382

In swing you'll want a JFileChooser.

public String promptForFolder( Component parent )
{
    JFileChooser fc = new JFileChooser();
    fc.setFileSelectionMode( JFileChooser.DIRECTORIES_ONLY );

    if( fc.showOpenDialog( parent ) == JFileChooser.APPROVE_OPTION )
    {
        return fc.getSelectedFile().getAbsolutePath();
    }

    return null;
}

It can be a little awkward selecting folders from a user's perspective. I've watched a lot of folks struggle with it. If you have the time you may want to try my DirectoryChooser. Sorry the code is so crufty; I wrote it awhile back.

Upvotes: 8

miku
miku

Reputation: 188164

You are looking for a FileChooser.

File choosers provide a GUI for navigating the file system, and then either choosing a file or directory from a list, or entering the name of a file or directory. To display a file chooser, you usually use the JFileChooser API to show a modal dialog containing the file chooser.

Upvotes: 3

Related Questions