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.

1 Answer 1

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

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

4 Comments

And check the size of the files array - it may be 0.
@MikeBaranczak Thanks for the heads up. Got a little lazy there.
Yeah, i didn't knew about FileDialog. This is a good solution. Thanks a lot !
@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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.