Calin Cretu Calin Cretu - 4 months ago 32
Java Question

Get the path of a file via file explorer

First of all I'm sorry if this question has been asked before or if there is documentation about the topic but i didn't found anything.
I want to make a windows app that open windows file explorer and you can browse for and then select a mp3 file, so you can play it (and replay it) in this program. I know how to open file explorer, this is my code :

import java.awt.Desktop;
public class Main
public static void main(String[] args) throws IOException {
Desktop desktop = Desktop.getDesktop();
File dirToOpen = null;
try {
dirToOpen = new File("c:\\");;
} catch (IllegalArgumentException iae) {
System.out.println("File Not Found");

But i don't know how to select an mp3 file and then get the path of the file, so i can play it later.


I don't think you are approaching this right. You should use something like a FileDialog to choose a file:

FileDialog fd = new FileDialog(new JFrame());
File[] f = fd.getFiles();
if(f.length > 0){

Since you are only getting 1 MP3 file, you only need the first index of the File array returned from the getFiles() method. Since it is a modal dialog, the rest of your application will wait until after you choose a file. If you want to get multiple files at once, just loop through this aforementioned Files array.

See the documentation here: