'How to return the file path from the windows file explorer using Java

In my Project, I want to open the windows file explorer with java, in which you can select a file or a folder and click the "OK" button. Now I want to have the path of the selected file in my Javacode.

Basically like the window which pops up in every standard texteditor after you hit the "OPEN" button to choose the file to open in the editor.

I know how to open the windows file explorer with Runtime.getRuntime().exec("explorer.exe") but I can´t figure out a way to return the file path.



Solution 1:[1]

This is how I'd use a JFileChooser for your problem:

String filePath;    // File path plus name and file extension
String directory;        // File directory
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        directory = fc.getSelectedFile().getName();
    } else {
        directory = "Error in selection";
    }
filePath = directory + "\\" + folderName;

Solution 2:[2]

The best option is to use JFileChooser class in javax.swing.JFileChooser. It's a Java swing object so it won't invoke the native OS's file browser but it does a good job at selecting a file/saving to a location. Take a look at this link on basic implementation of it.

I used this method from the link in my code:

public static Path getInputPath(String s) {
        
         /*Send a path (a String path) to open in a specific directory
         or if null default directory */
         JFileChooser jd = s == null ? new JFileChooser() : new JFileChooser(s);

         jd.setDialogTitle("Choose input file");
         int returnVal= jd.showOpenDialog(null);

         /* If user didn't select a file and click ok, return null Path object*/
         if (returnVal != JFileChooser.APPROVE_OPTION) return null;
         return jd.getSelectedFile().toPath();
    
    }

Note that this method returns a Path object, not a String path. This can be changed as needed.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Molly Taylor
Solution 2 sleeplessCode