Easy way to select a file

Is there an easy way to select the file path in Java? I have searched around and it JFileChooser

keeps going up, but this is too over the top for what I want now, as it seems like it requires building the entire GUI. I'll do this if need be, but is there an easier way to get the file path?

I'm wondering if there is something like a dialog box JOptionPane

for finding the file path.

+3


source to share


3 answers


If you don't have a surrounding interface you can just use it (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;
    }
}

      

+2


source


Here's the simplest 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 connect this action to, for example, a button and this. Your button will open a graphical interface to select a file, and if the user selects a file JFileChooser.APPROVE_OPTION

, you will be able to perform the required action (this only logs what was opened)

See oracle documentation ( https://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html ) if you want to do something else (don't bind a button?) Or something more complex (filter only for some extensions? ...)

+1


source


JFileChooser is not that hard if you only need to select 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


source







All Articles