Simple way to choose a file

93 views Asked by At

Is there some simple way to choose a file path in Java? I've been searching around, and JFileChooser keeps coming up, but that's already too excessive for what I want now, as it seems to require making a whole GUI just for that. I'll do it if need be, but is there a simpler way to get the file path?

I'm wondering if there's something like a JOptionPane dialog box to search for the file path.

3

There are 3 answers

1
Max Fichtelmann On BEST ANSWER

When you have no surrounding UI, you can simply use this (based on the Answer from Valentin Montmirail)

public static void main( String[] args ) throws Exception
{
    JFileChooser fileChooser = new JFileChooser();
    int returnValue = fileChooser.showOpenDialog( null );

    switch ( returnValue )
    {
    case JFileChooser.APPROVE_OPTION:
        System.out.println( "chosen file: " + fileChooser.getSelectedFile() );
        break;
    case JFileChooser.CANCEL_OPTION:
        System.out.println( "canceled" );
    default:
        break;
    }
}
0
kjp On

JFileChooser is not that complicated if you only need to choose a file.

public class TestFileChooser extends JFrame {
    public void showFileChooser() {
        JFileChooser fileChooser = new JFileChooser();
        int result = fileChooser.showOpenDialog(this);
        if (result == JFileChooser.APPROVE_OPTION) {
            File selectedFile = fileChooser.getSelectedFile();
            System.out.println("Selected file: " + selectedFile.getAbsolutePath());
        }
    }
    public static void main(String args[]) {
        new TestFileChooser().showFileChooser();
    }
}
0
Valentin Montmirail On

Here is the simpliest way to choose a file path in Java :

public void actionPerformed(ActionEvent e) {
    //Handle open button action.
    if (e.getSource() == openButton) {
        int returnVal = fc.showOpenDialog(YourClass.this);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            //This is where a real application would open the file.
            log.append("Opening: " + file.getName() + "." + newline);
        } else {
            log.append("Open command cancelled by user." + newline);
        }
   } ...
}

You can plug this actionPerformed to a button for example, and that's it. Your button will open a GUI to select a file, and if the user select the file JFileChooser.APPROVE_OPTION, then you can perform the action that you want (here only logging what was opened)

See the oracle documentation (https://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html) if you want to do something else (not binding a button ?) or something more complex (filter for some extensions only ? ...)