How to choose file in java? [duplicate]
Asked Answered
D

1

10

I need to get file path for my java program during runtime. Is there any way to use default dialog box to choose a single file and get its full path and name?

Its just picking a file and get its path into a String object

Can you please provide the code for it or a tutorial?

PS: Windows OS

Dele answered 26/10, 2016 at 6:19 Comment(6)
Is it a GUI program that you are looking for? what application are you trying to build?Gallinule
If you are using swing JFileChooser or FileDialog if you are using javafx, FileChooser. The JFileChooser doc has an example of usage.Flyover
@shreyas-sarvothama Yes I'm looking for GUI File chooserDele
Then as @Flyover suggested, go for JFileChooser... I would recommend you to take a complete Java Tutorial. JavaFx if you are looking for GUIGallinule
If you don't have a preference for JavaFx or Swing, go for JavaFx. It is a modern GUI that Oracle actively developes these days (where Swing has not changed in more than 10 years).Forensics
Thanks for your help guysDele
F
35

Here is the example from the JFileChooser docs copy pasta with the parent sent to null.

public class PickAFile {
    public static void main(String[] args){
        JFileChooser chooser = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter(
                "JPG & GIF Images", "jpg", "gif");
        chooser.setFileFilter(filter);
        int returnVal = chooser.showOpenDialog(null);
        if(returnVal == JFileChooser.APPROVE_OPTION) {
            System.out.println("You chose to open this file: " +
                    chooser.getSelectedFile().getName());
        }
    }
}

If you don't like the look of the JFileChooser try the FileDialog.

    FileDialog dialog = new FileDialog((Frame)null, "Select File to Open");
    dialog.setMode(FileDialog.LOAD);
    dialog.setVisible(true);
    String file = dialog.getFile();
    dialog.dispose();
    System.out.println(file + " chosen.");

** The call to dispose is necessary to exit the program if this is an isolated call, or to prevent a memory leak if this is used in a larger application.

Flyover answered 26/10, 2016 at 6:29 Comment(5)
Thanks a lot. It worked!!Dele
Is there a way to get the full Path? Figured it out thanks for post. chooser.getSelectedFile().getAbsolutePath());Expeller
to add extention filter to FileDialog you can go FileDialog dialog =.... ; dialog.setFile("*.jpg;*.png;*.jpeg");Evermore
You need to dispose of the dialog window after using it or the process hangs at termination: dialog.dispose()Becker
@Becker good catch. If it was a swing JDialog, I would use the setDefaultCloseOperation but the FileDialog is AWT so you're completely correct.Flyover

© 2022 - 2024 — McMap. All rights reserved.