Hemanth S. Vaddi Hemanth S. Vaddi - 1 year ago 170
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 Source

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");
        int returnVal = chooser.showOpenDialog(null);
        if(returnVal == JFileChooser.APPROVE_OPTION) {
            System.out.println("You chose to open this file: " +

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

    FileDialog dialog = new FileDialog((Frame)null, "Select File to Open");
    String file = dialog.getFile();
    System.out.println(file + " chosen.");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download