3

In a lot of programs, there is an option to locate a particular file using the native OS file explorer. How can this functionality be implemented using java?

3
  • 1
    Are you using Android, AWT, SWT, Swing, JavaFX, ...? Commented May 10, 2019 at 5:06
  • For swing, there's JFileChooser Commented May 10, 2019 at 5:32
  • I'm using javafx but should that matter? It'll be great to have a native window open up with the selected file highlighted. Commented May 10, 2019 at 6:21

3 Answers 3

2

Java provides java.awt.Desktop (API JDK 11), with which such interactions can be made:

File file = new File("/path/to/file.txt"); Desktop.getDesktop().open(file.getParentFile()); 

I use file.getParentFile() to open the directory containing the file, and not the file itself. If this line is executed, Finder (on macOs), Explorer (on Windows), or the default file browser on Linux will open a new window with the specified directory.

Sign up to request clarification or add additional context in comments.

Comments

0

What about file chooser?

FileChooser fileChooser = new FileChooser(); fileChooser.setInitialDirectory(new File("data")); fileChooser.setInitialFileName("myfile.txt"); fileChooser.getExtensionFilters().addAll( new FileChooser.ExtensionFilter("Text Files", "*.txt") ,new FileChooser.ExtensionFilter("HTML Files", "*.htm") ); File selectedFile = fileChooser.showOpenDialog(stage); 

More on http://tutorials.jenkov.com/javafx/filechooser.html

Comments

0

The only working solution to this on macos is this one:

ProcessBuilder pb = new ProcessBuilder("/usr/bin/open", "-R", pathName); pb.start(); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.