Hemanth S. Vaddi Hemanth S. Vaddi - 1 month ago 15
Java Question

How to choose file in java?

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

Answer

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();
    System.out.println(file + " chosen.");
Comments