Load file in java with special path name - java

i try to play an mp3 from an location on my harddrive.
The file is located in here:
C:\Itunes\Music\Eminem\The Eminem Show [Explicit]\18 'Till I Collapse [Explicit].mp3
There are a lot of special characters in this path like [ and '. When i try to load the file with following code:
path = URLEncoder.encode(path, "UTF-8");
Media hit = new Media("file:///"+path);
MediaPlayer mediaPlayer = new MediaPlayer(hit);
mediaPlayer.play();
i get an "illegal character" error in pathname.
My operating system is windows 8.
I'm very new to java and hope i find some help.

I believe you need to encode your URI
See: http://blogs.msdn.com/b/ie/archive/2006/12/06/file-uris-in-windows.aspx

Related

How do I specify file path for Android's getExternalStorageState()?

I'm completely new to Android development and would like to index a file from the Android phone's external storage. I found some old code which used a deprecated method:
String file1 = Environment.getExternalStorageDirectory() + "/folder/file.blah";
I'm trying to rewrite this line and tried the Environment.getExternalFilesdir method but got a "cannot find symbol method" error. The only available method seems to be getExternalStorageState, but I can't figure out how to pass the file path argument in. How do I rewrite the deprecated code, using getExternalStorageState or otherwise? Thanks.
For getting directory of public file. you can use like below
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOCUMENTS);
docFile = new File(storageDir, docFileName);
Actually getExternalFilesDir() is not a part of Environment bundle. You can call it via the application context.
String file2 = getApplicationContext().getExternalFilesDir("folder")
The difference between these two are as follows
getExternalFilesDir():
This will return the path to files folder inside Android/data/data/your_package_name/. It is used to store any required files for your app.
getExternalStorageDirectory():
This returns the root path of you external SD card.
As far as the deprecation warning is concerned, Environment.getExternalStorageDirectory() or Environment.getExternalStoragePublicDirectory(), are deprecated. They still work, but will be removed soon, so you need to stop using those.

Slash character in file path creating exception in javafx media

I found many similar questions on this topic in this forum, but none of the solutions of those questions working for me and this problem is really making me frustrated.
I have the following method which should play a wav file when I call it.
Directory of the wav file is: ProjectFolder/src/resources/Sounds/click.wav
public static void Click()
{
String clickSound = "/resources/Sounds/click.wav";
Media hit = new Media(new File(clickSound).toPath().toString());
MediaPlayer mediaPlayer = new MediaPlayer(hit);
mediaPlayer.play();
}
But it results in the following exception:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: java.net.URISyntaxException: Illegal character in path at index 0: \resources\Sounds\click.wav
at javafx.scene.media.Media.<init>(Media.java:385)
When I set the value of the string clickSound "resources/Sounds/click.wav" instead of "/resources/Sounds/click.wav", the exception says illegal character in path at index 9.
So I am guessing that it is considering '/' character as an illegal character. I tried using '\' instead of '/', but the result was same.
I do not want to change the location of the wav file for certain reason. How can access I access that wav file from ProjectFolder/src/resources/Sounds/click.wav and play it without any exception?
Any kind of help is appreciated.
Thanks in advance.
As stated in the documentation:
The source must represent a valid URI and is immutable. Only HTTP, HTTPS, FILE, and JAR URLs are supported. If the provided URL is invalid then an exception will be thrown.
You are passing in the path to a file, instead of a URI.
You almost certainly don't want a file here anyway; for example, when you deploy your application it will typically be deployed as a jar file, and the media will be an entry in that jar file (so it won't be a file in its own right at all). On top of that, the resources folder is typically part of the source code structure, and for obvious reasons the source code is not usually available at runtime.
Assuming your resources are being deployed to the root of the classpath, which is the usual setup, you need something like
String clickSound = "/Sounds/click.wav";
Media hit = new Media(getClass().getResource(clickSound).toExternalForm());
You listed the file as in directory "ProjectFolder/src/resource/Sounds/click.wav" but when trying to access you have "resources" instead of "resource"

Cannot retrieve native file ffmpeg-amd64.exe

I am trying to convert video to audio . That is why , I am using the following code :
File source = new File("E:\\Shunno - Khachar Bhitor Ochin Pakhi.mp4");
File target = new File("E:\\output.mp3");
AudioAttributes audio = new AudioAttributes();
audio.setCodec("libmp3lame");
audio.setBitRate(new Integer(128000));
audio.setChannels(new Integer(2));
audio.setSamplingRate(new Integer(44100));
EncodingAttributes attrs = new EncodingAttributes();
attrs.setFormat("mp3");
attrs.setAudioAttributes(audio);
Encoder encoder = new Encoder();
try
{
encoder.encode(source, target, attrs);
}
catch (IllegalArgumentException | EncoderException e)
{
}
But I am getting the following error :
Sep 26, 2016 11:28:29 AM it.sauronsoftware.jave.DefaultFFMPEGLocator copyFile
SEVERE: Could not get native library for ffmpeg-amd64.exe
Exception in thread "main" java.lang.RuntimeException: Cannot retrieve native file ffmpeg-amd64.exe
at it.sauronsoftware.jave.DefaultFFMPEGLocator.copyFile(DefaultFFMPEGLocator.java:139)
at it.sauronsoftware.jave.DefaultFFMPEGLocator.<init>(DefaultFFMPEGLocator.java:80)
at it.sauronsoftware.jave.Encoder.<init>(Encoder.java:105)
at Convert.main(Convert.java:29)
How can I solve this error ? Please help me .
The error is very clear: ffmpeg cannot been found.
Since you hard coded some windows path here is the windows binary of ffmpeg. I suggest to download the x64 static version. Since that is just one file you need to care about.
If you need it for another platform check the download site.
Within the zip file in the subdirectory bin where the binary ffmpeg.exe is located. Now you need to renamed it to ffmpeg-amd64.exe since the library expects that name. Now you need to copy the file to a directory of your path variable e.g. C:\windows\system32. I suggest not to use that directory, but this is the simplest way. Better put it somewhere else and modify your path variable. There are dozens of explanations so just google them if you want how do achieve that.

Playing an mp3 file in BlueJ

I'm trying to play an mp3 file in BlueJ following this Stack question answer:
Playing .mp3 and .wav in Java?
I have the exact same code except the file name. Here is my code:
String bip = "Johnny.mp3";
Media hit = new Media(bip);
MediaPlayer mediaPlayer = new MediaPlayer(hit);
mediaPlayer.play();
I CAN compile this, but when the program tries to run it I get an exception. Here is the entire error:
java.lang.IllegalArgumentException: uri.getScheme() == null! uri == 'Johnny.mp3'
at com.sun.media.jfxmedia.locator.Locator.<init>(Locator.java:211)
at javafx.scene.media.Media.<init>(Media.java:391)
at Game.goRoom(Game.java:282)
at Game.processCommand(Game.java:167)
at Game.play(Game.java:130)
Personally, I think this is related with the file path I have given. I know that the file exists in my project map but I'm very uncertain on the pathway they want, do they want a full pathway all the way from file:// or just the sound-files name which is what I have done? Note that this project doesn't have any resource folder like Eclipse projects have since this is how the IDE handles it files. The sound-file just lies in the same folder as all the classes so it's not sorted in any manner.
I have checked around, and it seems that if this is not my problem it would be that my JavaFX is not initialized. If this is the case, how would I go about it and how would the syntax look like?
Media takes your String value and tries to make a URI. Why the method doesn't just require you to pass it a URI (or URL) directly, I don't know.
The documentation outlines this rather well...
Constructs a Media instance. This is the only way to specify the media
source. The source must represent a valid URI and is immutable. Only
HTTP, FILE, and JAR URLs are supported. If the provided URL is invalid
then an exception will be thrown. If an asynchronous error occurs, the
error property will be set. Listen to this property to be notified of
any such errors.
...
Constraints:
The supplied URI must conform to RFC-2396 as required by java.net.URI.
Only HTTP, FILE, and JAR URIs are supported.
See java.net.URI for more information about URI formatting in
general. JAR URL syntax is specified in
java.net.JarURLConnection.
Parameters: source - The URI of the source media. Throws:
- java.lang.NullPointerException - if the URI string is null.
- java.lang.IllegalArgumentException - if the URI string does not
conform to RFC-2396 or, if appropriate, the Jar URL specification, or
is in a non-compliant form which cannot be modified to a compliant
form. - java.lang.IllegalArgumentException - if the URI string has a
null scheme. - java.lang.UnsupportedOperationException - if the
protocol specified for the source is not supported....
And if we have a look at the source, you can see it trying to wrap the String in a URI class...
public Media(#NamedArg("source") String source) {
this.source = source;
URI uri = null;
try {
// URI will throw NPE if source == null: do not catch it!
uri = new URI(source);
} catch(URISyntaxException use) {
throw new IllegalArgumentException(use);
}
So, depending on where the file is actually stored, you could use something like
Media hit = new Media(new File(bip).toURI().toURL().toString());
MediaPlayer mediaPlayer = new MediaPlayer(hit);
mediaPlayer.play();
This also assumes that "Johnny.mp3" is in the current working directory of your program.
I say "depending" as you would use a different approach for media files which were located internally (bundled) with your application to those which are external.
In which case you might use something like...
Media hit = new Media(getClass().getResource(bip).toExternalForm());
MediaPlayer mediaPlayer = new MediaPlayer(hit);
mediaPlayer.play();
Here ya go:
MediaPlayer yourPlayer = new MediaPlayer(new Media(Paths.get("yourAudioFile").toUri().toString()));
Make sure to add the file extension onto the audio file! Also, import the following:
import java.nio.file.Paths;
I'm assuming you have the Media and MediaPlayer classes imported.

java.net.URISyntaxException

I have get this exception. but this exception is not reproduced again. I want to get the cause of this
Exception Caught while Checking tag in XMLjava.net.URISyntaxException:
Illegal character in opaque part at index 2:
C:\Documents and Settings\All Users\.SF\config\sd.xml
stacktrace net.sf.saxon.trans.XPathException.
Why this exception occured. How to deal with so it will not reproduce.
A valid URI does not contain backslashes, and if it contains a : then the characters before the first : must be a "protocol".
Basically "C:\Documents and Settings\All Users\.SF\config\sd.xml" is a pathname, and not a valid URI.
If you want to turn a pathname into a "file:" URI, then do the following:
File f = new File("C:\Documents and Settings\All Users\.SF\config\sd.xml");
URI u = f.toURI();
This is the simplest, and most reliable and portable way to turn a pathname into a valid URI in Java. It should work on Windows, Mac, Linux and any other platform that supports Java. (Other solutions that involve using string bashing on a pathname are not portable.)
But you need to realize that "file:" URIs have a number of caveats, as described in the javadocs for the File.toURI() method. For example, a "file:" URI created on one machine usually denotes a different resource (or no resource at all) on another machine.
The root cause for this is file path contains the forward slashes instead of backward slashes in windows.
Try like this to resolve the problem:
"file:" + string.replace("\\", "/");
You must have the string like so:
String windowsPath = file:/C:/Users/sizu/myFile.txt;
URI uri = new URI(windowsPath);
File file = new File(uri);
Usually, people do something like this:
String windowsPath = file:C:/Users/sizu/myFile.txt;
URI uri = new URI(windowsPath);
File file = new File(uri);
or something like this:
String windowsPath = file:C:\Users\sizu\myFile.txt;
URI uri = new URI(windowsPath);
File file = new File(uri);
It needs a complete uri with type/protocol
e.g
file:/C:/Users/Sumit/Desktop/s%20folder/SAMPLETEXT.txt
File file = new File("C:/Users/Sumit/Desktop/s folder/SAMPLETEXT.txt");
file.toURI();//This will return the same string for you.
I will rather use direct string to avoid creating extra file object.
I had the same "opaque" error while passing a URI on the command line to a script. This was on windows. I had to use forward slashes, NOT backslashes. This resolved it for me.
it doesn't like spaces as well and it has to be / instead of \ or `\ or //
zipFilePath = "C:/test/v";

Categories

Resources