3

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.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
Copacel
  • 1,328
  • 15
  • 25

1 Answers1

3

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

A.Sharma
  • 2,771
  • 1
  • 11
  • 24
  • And check the size of the files array - it may be 0. – Mike Baranczak Sep 07 '16 at 18:16
  • @MikeBaranczak Thanks for the heads up. Got a little lazy there. – A.Sharma Sep 07 '16 at 18:18
  • Yeah, i didn't knew about FileDialog. This is a good solution. Thanks a lot ! – Copacel Sep 07 '16 at 18:24
  • @A.Sharma I'd like to add that you have to set the multiple files through `FileDialog.setMultipleMode(bool);` however, this only applies for JDK7 and above. [link](https://stackoverflow.com/questions/5182100/how-to-select-multiple-files-using-java-awt-filedialog) – CraftedGaming Jul 11 '17 at 04:02