Calin Cretu Calin Cretu - 2 months ago 15
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;
import java.io.File;
import java.io.IOException;
public class Main
{
public static void main(String[] args) throws IOException {
Desktop desktop = Desktop.getDesktop();
File dirToOpen = null;
try {
dirToOpen = new File("c:\\");
desktop.open(dirToOpen);
} 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.

Answer

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());
fd.setVisible(true);
File[] f = fd.getFiles();
if(f.length > 0){
    System.out.println(fd.getFiles()[0].getAbsolutePath());
}

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: https://docs.oracle.com/javase/7/docs/api/java/awt/FileDialog.html

Comments