How to open a file with a double click rather than JFileChooser - java

I created a mp3 player in java and then created it as a .exe file. Now to play song in mp3 player I have to choose song in JFileChooser then it plays that song.
if (chooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) {
Path=chooser.getSelectedFile().getAbsolutePath().replace('\\','/');
But I want that when I double click on that song in Windows explorer or in My Computer it will play that song directly like VLC or other player do. We don't need to first choose the song in a file chooser, we just need to click on a song and it play.

Adding to Raymond Holguin's answer in your main method save the first parameter and if its a File that exists then send it to your player class and set to start playing (not show UI with play button)
public static void main(String args){
if(args.length > 0){
java.io.File possibleAudioClipFile = new File(args[0]);
if(possibleAudioClipFile.exists() && possibleAudioClipFile.isFile.isFile() && possibleAudioClipFile.canRead()){
/might want to check extn or first few bytes then play or show error msg and exit/ show default UI
}
}
besides you need to make sure each customer/user has your app assocaited with the audio file types by extention name . Can use a script in command propmt using assoc http://support.microsoft.com/kb/323526 or in windows explorer Tools/Options menu.

This is a windows config issue, and possibly an application issue.
1) In windows you need to make the association with .mp3 files that says whenever an MP3 is opened to use your program. If you right click on an MP3 -> Open With you can choose the defalut program for that file type
2) In your program you need to handle the file information that is going to be passed into your application in order to open it. So instead of using File info from JChooseer your going to use the File info that is passed as an input into your application.

You need to associate your application with the filetypes you support. On Windows, this means creating an association to a URI scheme in the registry. See here: https://msdn.microsoft.com/en-us/library/ie/aa767914%28v=vs.85%29.aspx
This is what happens when you right-click and choose what executable to open a particular file type with.

Related

JFileChooser file filtering doesn't actually filter (at least as I intend it to)

I'm trying to set a JFileChooser to only allow choosing a specific file type (pdf) via the showOpenDialog.
I've set a File Filter but I'm confused as to what action on the JFileChooser it has.
What I'm trying to achieve is:
Visually exclude other file types to prevent the user from choosing them from the list.
Actually prevent selection of other types or an invalid file. (i.e. have the getSelectedFile() to actually return a valid pdf file)
Here is my code:
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
fc.setAcceptAllFileFilterUsed(false);
fc.setFileFilter(new FileNameExtensionFilter("PDF Files", "pdf"));
fc.setDialogTitle("Load MSDS");
int op = fc.showOpenDialog(this);
if(op == JFileChooser.APPROVE_OPTION) {
File f = fc.getSelectedFile();
lbl_msds_loaded.setForeground(Color.BLACK);
lbl_msds_loaded.setText(f.getName() + " (Size: " + utils.FileUtils.getFileSizeMegaBytes(f, 3) + ")");
}
I get this behavior:
Visually - The filtering works and the dialog does only show PDF Files, therefore I can only choose pdf files from the list.
But - I'm still able to manually select an invalid file, by typing in some name in the 'File name:' field and click open (or hit enter).
For example: if I write Untitled.png (which does exist in the currently opened directory) and open, I will get that png file loaded.
Or if write a file name that doesn't exist and click open, I will actually get a new file with that name loaded.
(By loaded I mean the file that getSelectedFile() will return).
Is there a way to not allow the dialog approve the open action if an invalid file is set (based on the filter ofcourse)?
Shouldn't this already be the case when using JFileChooser Dialogs with filters?
What exactly is the filter doing here? The documentation for JFileChooser does not explain any of these aspects.
I would really appreciate an explanation on how this works.
Also what is the difference between setFileFilter and addChoosableFileFilter? They give the exact same behavior.
Finally here's a few screenshots of the Dialog and the JFrame form I'm working on for some context:
https://ibb.co/bFVqVmt
https://ibb.co/5BcsXSW
https://ibb.co/2qq0qr9
https://ibb.co/jMXXXyN
https://ibb.co/g3kvtfd
https://ibb.co/2FshJpt
Thanks alot!

Clear file name when enter directory name and enter

I'm working on opening a file using JFileChooser Here is my code
JFileChooser fileChooser = new JFileChooser();
fileChooser.setAcceptAllFileFilterUsed(false);
FileNameExtensionFilter filter = new FileNameExtensionFilter("FF Files", "ff");
fileChooser.addChoosableFileFilter(filter);
int result = fileChooser.showDialog(null, "PP");
on a button click event these code will be running, very normal code I guess. When I click it, the JFileChooser dialog appears. If I enter a directory name in the File Name field (Ex. sam) and hit Enter, it enters to the directory, but the text field still shows the entered text i.e 'sam' I tried the same flow in notepad and in eclipse, in that phase, 'sam' getting cleared so that I can provide another directory name and hit enter.
Correct me if my code is wrong, If this problem is duplicate, I apology for wasted your time.
Notepad and Eclipse use a different implementation than JFileChooser. That´s why it might behave different and I don´t think you can do anything to make it work like you are expecting it (instead of using a custom library or making your own implementation).

Extracting files from res folder in Executable JAR (txt files to be specific)

I would like to ask if its possible to put text files into my jar, I use them to make my map in my game, but users can get Highscores. now I want to save the Highscores with the map, so I have to save the map on the user their PC. Is there any way how I could do this? I've searched the internet for some ideas but I could not find anything that even came close to what I've wanted. I only had 3/4th of a year java so I don't know much about these things, everything that happens outside the debug of eclipse are problems for me(files are mainly one of those things, null exceptions, etc).
The main question now.
Is it possible to do? If yes, do you have any terms I could search on, or some sites/guides/tutorials? If no, is there any other way how I could save the highscores?
EDIT:
to make clear
Can I get the text file (the text inside the file) to be extracted to a different file in like the home directory of my game (where I save the settings and stuff) the basic maps are inside the jar file, so I want them to be extracted on the first start-up of the program
Greetings Carolien
"extracted to a different file in like the home directory of my game (where i save the settings and stuff) the basic maps are inside the jar file, so i want them to be extracted on the first startup of the program"
You can get the URL by using getClass().getResource()
URL url = getClass().getResource("/res/myfile.txt");
Then create a File object from the URI of the URL
File file = new File(url.toURI());
Then just perform your normal file operations.
if (file.renameTo(new File(System.getProperty("user.home") + "\\" + file.getName()))) {
System.out.println("File is moved successful!");
} else {
System.out.println("File is failed to move!");
}
Assuming your file structure is like below, it should work fine
ProjectRoot
src
res
myfile.txt
Note: the above is moving the entire file. If you want to extract just the data inside the file, then you can simple use
InputStream is = getClass().getResourceAsStream("/res/myfile.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
The just do normal IO operation with the reader. See here for help with writing the file.

Open a byte[] as a file From a javaapplication, User should not be able to edit the file

I am currently opening the file like this:
File f = File.createTempFile(prefix, suffix);
f = FileUtil.writeBytes(b.getBlob(), f);
Desktop.getDesktop().open(f);
Context description :
The file is stored on a server. When you want to view the file the byte[] is retrieved from the server and is put in a File object (see line 2 of code sample above).
Now when the user opens the file (for instance txt file) it is possible to edit and save the file (it does not even ask for a fileName, because you have given when creating the File based on the blob in the above sample).
However I don't want this behaviour. I want the file save to behave as 'save as" similar to a non existing file.
In short:
I have :
A byte[] containing content of a .txt that is located on a server
I want
To be able to open the file in the associated program (notepad for instance) without actually creating the File on the client PC. When the user would press save, it should be prompted for a fileName, just like when saving a new file for the first time.
How should I go about this?
Example of behaviour I want: behaviour as Mail attachment in email client like thunderbird for example. When clicking on txt attachment it asks me to a)open with ... , or b) save to ... . If i choose open with, and then in text editor I choose save, it prompts me for a name and location.
Undoable. Even if you, a bit after opening the temporary file, would delete the file, for instance Notepad would not see it. Others would ask to recreate at the same spot.
Would an alternative not suffice: first a "create new" - a file save dialog -, you create the file where desired, and then do a Desktop.open.

Specifying file location for PrintWriter class (Java) and automatically appending .txt

so let's say I ask the user to specify what he wants to call a new file
System.out.println("What do you want to call the file?");
String outputFile = keyboard.nextLine();
now to write the file I would do:
PrintWriter outputFile = new PrintWriter(fileName);
My question are:
I know by default it saves to the local folder. How do I make it so that it will save it to the users desktop?
How do I automatically append .txt to his given file name so he doesn't have to do it?
You have to know the user home. It can vary with the OS (and the user can sometimes define its own), so the best way to be sure is to ask directly the user. You could also keep a list of "default desktop paths".
if(!fileName.endsWith(".txt")) fileName = fileName+".txt";
Resources:
String.endsWith()
If you're going to ask the user where to put the file, you should probably start with the directory that is given by the system property "user.home", i.e. call System.getProperty("user.home");
Then you could show a list of directories and ask the user to choose one, drilling down until the user is at the directory he wants to use. On Windows machines, the "Desktop" directory is in fact immediately under the user's home directory.

Categories

Resources