I was trying to use MP3s instead of wavs and it works fine in NetBeans, but when I build it and try to run the jar there's no sound and I get the NoPlayerException.
background = ImageIO.read(getClass().getResourceAsStream("/background1.png"));
sun = ImageIO.read(getClass().getResourceAsStream("/sun.png"));
cloud = ImageIO.read(getClass().getResourceAsStream("/cloud.png"));
pause = ImageIO.read(getClass().getResourceAsStream("/pause.png"));
soldierchant = AudioSystem.getAudioInputStream(getClass().getResource("/SoldiersChant.wav"));
thebreach = AudioSystem.getAudioInputStream(getClass().getResource("/TheBreach.wav"));
forever = AudioSystem.getAudioInputStream(getClass().getResource("/Forever.wav"));
Format input1 = new AudioFormat(AudioFormat.MPEGLAYER3);
Format input2 = new AudioFormat(AudioFormat.MPEG);
Format output = new AudioFormat(AudioFormat.LINEAR);
PlugInManager.addPlugIn("com.sun.media.codec.audio.mp3.JavaDecoder", new Format[]{input1, input2}, new Format[]{output}, PlugInManager.CODEC);
try {
Player player = Manager.createPlayer(new MediaLocator(getClass().getResource("/TheBreach.mp3").toURI().toURL()));
player.start();
} catch (IOException ex) {
ex.printStackTrace();
}catch (java.net.URISyntaxException x) {
x.printStackTrace();
}catch (javax.media.NoPlayerException c) {
c.printStackTrace();
}
As you can see I'm getting the file from using getResource just like the images and wav that work both in NetBeans and jar. Could this be the problem com.sun.media.codec.audio.mp3.JavaDecoder
I'm grabbing at straws at this point. I've tried putting the MP3 in every folder and doing no / and the full directory.
This is my Exception's getMessage:
Cannot find a Player for jar:file:/C:/Users/Patrick/Documents/NetBeansProjects/PatBuild8FX/dist/PatBuild8FX.jar!/TheBreach.mp3
I think it is Manager.createPlayer because when I just create the file alone its fine, but when I try to create a player with it, it doesn't work.
File m = new File("file:/C:/Users/Patrick/Documents/NetBeansProjects/PatBuild8FX/dist/PatBuild8FX.jar/TheBreach.mp3");
System.out.println(m);
System.out.println(Manager.createPlayer(m.toURI().toURL()));
file:\C:\Users\Patrick\Documents\NetBeansProjects\PatBuild8FX\dist\PatBuild8FX.jar\TheBreach.mp3
java.io.IOException: File Not Found
java.io.IOException: File Not Found
Exception in thread "main" javax.media.NoPlayerException: Error instantiating class: com.sun.media.protocol.file.DataSource : java.io.IOException: File Not Found
at javax.media.Manager.createPlayerForContent(Manager.java:1362)
at javax.media.Manager.createPlayer(Manager.java:417)
at javax.media.Manager.createPlayer(Manager.java:332)
at Build8.PanGame.<init>(PanGame.java:75)
at Build8.Main.main(Main.java:30)
Did you package the 'TheBreach.mp3' file into your jar file? The exception message above suggests that the resource is being accessed from your jar file.
My suggestions:
if you haven't already done so, package the .mp3 file into the jar file (this makes it easier for you to move the single jar file without having to copy the .mp3 file along with it, and also the mp3 file should now be accessible from the jar file), or
if you prefer to have the .mp3 file where it is, then try using a java.io.File class to load the mp3 file before passing to the MediaLocator constructor. Hence, you'd then have something like:
new MediaLocator(new File("file:///C:\\full_path_to_the_file\\TheBreach.mp3").toURL())
finally, the documentation for MediaLocator.createPlayer() explaining issues with creating players should be handy. You can find it here
Good luck!
Related
So my task is to create a small program that displays a list of media files and run these media files with default OS media player separately.
My current solution was to create a package that holds all media files, something like:
-com.media
|_a.mp4
|_b.mp4
The following code copies to a temp dir the selected mp4, then runs the default os media player:
public File copyTempMedia(File tempAppFolder, String videoName) {
URL f = getClass().getResource(String.format("%s/%s", Constants.MEDIA_LOCATION, videoName));
File from = new File(f.getPath());
File to = new File(tempAppFolder.getAbsolutePath());
try {
FileUtils.copyFileToDirectory(from, to);
} catch (IOException ex) {
Logger.getLogger(MediGUIModel.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("Temp video copied: " + to.getAbsolutePath() + "/" + to.getName());
return to;
}
public void triggerMediaPlayer(String fileLocation) {
System.out.println("Triggering media player: " + fileLocation);
try {
if (OPERATIN_SYSTEM.contains("Linux")) {
Runtime.getRuntime().exec("sh -c " + fileLocation);
} else if (OPERATIN_SYSTEM.contains("Windows")) {
Runtime.getRuntime().exec("cmd /c " + fileLocation);
}
} catch (IOException ex) {
Logger.getLogger(MediGUIModel.class.getName()).log(Level.SEVERE, null, ex);
ex.printStackTrace();
}
}
When I run the program through Netbeans it works as espected, but when I do a clean/build the run the .jar created from the build, the media file doesn't seem to be read, so my questions are:
Why does it work through Netbeans and not through build .jar ?
Is this the best solution to this problem ?
Should I package the media differently ?
Thanks in advance.
Edit
So after running through console instead of double clicking jar, is get a null pointer exception in the line where I read the file:
URL f = getClass().getResource(String.format("%s/%s", Constants.MEDIA_LOCATION, videoName));
Why does it work in Netebeans but not on build/jar ?
Is there another place in the jar I could place the media files, so that they are read with no problem through getResource or getResourceAsStream ?
When you run the project in NetBeans, it isn't running the executable jar like java -jar yourproject.jar. Instead it sets the classpath to build/classes sort of like java -cp build/classes com.media.YourMainClass. This means your video files are actual files located in yourproject/build/classes/com/media, and they can be accessed as normal files in the filesystem and copied like a normal file. When you run from the jar, the files are packed in the jar file and can't be copied using simple file copy commands.
Instead of getting the URL by calling getClass().getResource(), try getting an InputStream by calling getClass().getResourceAsStream(). You can then write a simple loop to copy the bytes from the input stream to your temporary file.
This snippet may be helpful:
BufferedInputStream result = (BufferedInputStream) getClass().getResourceAsStream("/com/media/a.mp4");
byte[] bytes = new byte[4098];
try {
result.read(bytes);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(new String(bytes));
You'll need to read the bytes in a loop or something but that should work without needing a separate jar.
I think it's not a good idea to put your media files in the jar because you need to rebuild the project if you want to change one and the jar size will grow.
Use:
File from = new File(String.format("%s/%s", Constants.MEDIA_LOCATION,videoName));
To load your files from the same folder as the jar.
If you want to keep the medias in the jar, create a Maven project and put the mp4 in src/main/resources.
Use maven to create a fat jar and the src/main/resources will be included in the jar.
See 'maven-shade-plugin' to configure the pom.xml and https://www.mkyong.com/maven/create-a-fat-jar-file-maven-shade-plugin/
Then you can use the others maven's great properties!
See Reading a resource file from within jar
Edit
After some tries, i can't get it right with 'getResource' from the jar.
The path you get from within the jar is like:file:/C:/.../JavaApplication4/dist/JavaApplication4.jar!/test.txt
and not recognized as a valid filesystem path.
You can use 'getResourceAsStream' and copy the file from the jar to the local folder.
InputStream in;
OutputStream out;
IOUtils.copy(in,out);
in.close();
out.close();
Ok so I found a solution:
Create a separate project with media.*.mp4.
Export as Jar library.
Import library to desktop app.
Make sure library is in classpath.
This solution works for me...
If anyone has a better solution, happy to hear, hopefully before bounty is up :)
I am making an simple application to play sounds in Java. I am able to do that when I keep the audio files in D: disk. Here is the code
in = new FileInputStream("D:\\"+selectedSounds[position]+".wav");
//Some code for playing audio
Then I placed the audio files in same package where the Jframe class is present. But when I run it prompts fileNotFound exception. Can some one tell me why this is happening.
in = new FileInputStream(selectedSounds[position]+".wav");
// I have also tried
new FileInputStream("./"+selectedSounds[position]+".wav");
Here is the file path
Your wave file, contained within the "Source Packages" won't be accessible once the program is packaged as a Jar, as the files will be embedded within the Jar itself and no longer accessible as files.
Instead, you should be using Class#getResourceAsStream, for example...
try (InputStream in = getClass().getResourceAsStream("/PlayAudio/" + selectedSounds[position]+".wav")) {
// You now have an InputStream to your resource, have fun
} catch (IOException | NullPointerException exp) {
exp.printStackTrace();
}
My Dataflow pipeline needs to read a resource file GeoLite2-City.mmdb. I added it to my project and ran the pipeline. I confirmed that the project package zip file exists in the staging bucket on GCS.
However, when I try to read the resource file GeoLite-City.mmdb, I get a FileNotFoundException. How can I fix this? This is my code:
String path = myClass.class.getResource("/GeoLite2-City.mmdb").getPath();
File database = new File(path);
try
{
DatabaseReader reader = new DatabaseReader.Builder(database).build(); //<-this line get a FileNotFoundException
}
catch (IOException e)
{
LOG.info(e.toString());
}
My project package zip file is "classes-WOdCPQCHjW-hRNtrfrnZMw.zip"
(it contains class files and GeoLite2-City.mmdb)
The path value is "file:/dataflow/packages/staging/classes-WOdCPQCHjW-hRNtrfrnZMw.zip!/GeoLite2-City.mmdb", however it cannot be opened.
and This is the options.
--runner=BlockingDataflowPipelineRunner
--project=peak-myproject
--stagingLocation=gs://mybucket/staging
--input=gs://mybucket_log/log.68599ca3.gz
The Goal is transform the log file on GCS, and insert the transformed data to BigQuery.
When i ran locally, it was success importing to Bigquery.
i think there is a difference local PC and GCE to get the resource path.
I think the issue might be that DatabaseReader does not support paths to resources located inside a .zip or .jar file.
If that's the case, then your program worked with DirectPipelineRunner not because it's direct, but because the resource was simply located on the local filesystem rather than within the .zip file (as your comment says, the path was C:/Users/Jennie/workspace/DataflowJavaSDK-master/eclipse/starter/target/classes/GeoLite2-City.mmdb, while in the other case it was file:/dataflow/packages/staging/classes-WOdCPQCHjW-hRNtrfrnZMw.zip!/GeoLite2-City.mmdb)
I searched the web for what DatabaseReader class you might be talking about, and seems like it is https://github.com/maxmind/GeoIP2-java/blob/master/src/main/java/com/maxmind/geoip2/DatabaseReader.java .
In that case, there's a good chance that your code will work with the following minor change:
try
{
InputStream stream = myClass.class.getResourceAsStream("/GeoLite2-City.mmdb");
DatabaseReader reader = new DatabaseReader.Builder(stream).build();
}
catch (IOException e)
{
...
}
I tried to open file form my java application. Using following code from
Open PDF file on fly from Java application
Code:
if (Desktop.isDesktopSupported()) {
try {
File myFile = new File("/path/to/file.pdf");
Desktop.getDesktop().open(myFile);
} catch (IOException ex) {
// no application registered for PDFs
}
}
When I use path like :
"C:\\Users\\kalathoki\\Documents\\NetBeansProjects\\TestJava\\src\\files\\test.pdf"
it opens. But my file is inside my package
files/test.pdf
and I used
files\\test.pdf
it shows following exception:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: The file: \files\test.pdf doesn't exist.
Why? Any Idea... I want to include my file inside my jar file that can open from my application whenever user wants.
Thanks...
getDesktop#open only allows files to be opened from the file system. One solution is to keep the PDF file locally on the file system and read from there. This eliminates extracting the file from the JAR itself so is more efficient.
Unfortunately, you cannot load a file through Desktop that is contained in the jar.
However, you are not out of options. A great workaround is to create a temporary file and then open it as detailed here.
Good luck!
Assuming test.pdf is in the package files, try this:
File myFile = new File(getClass().getResource("/files/test.pdf").toURI());
This code is working properly please use this to open pdf file within jar file
try {
// TODO add your handling code here:
String path = jTextField1.getText();
System.out.println(path);
Path tempOutput = null;
String tempFile = "myFile";
tempOutput = Files.createTempFile(tempFile, ".pdf");
tempOutput.toFile().deleteOnExit();
InputStream is = getClass().getResourceAsStream("/JCADG.pdf");
Files.copy(is,tempOutput,StandardCopyOption.REPLACE_EXISTING);
if(Desktop.isDesktopSupported())
{
Desktop dTop = Desktop.getDesktop();
if(dTop.isSupported(Desktop.Action.OPEN))
{
dTop.open(tempOutput.toFile());
}
}
} catch (IOException ex) {}
I've a .txt file ("file.txt") in my netbeans "/build/classes" directory.
In the same directory there is the .class file compiled for the following code:
try {
File f = new File("file.txt");
Scanner sc = new Scanner(f);
}
catch (IOException e) {
System.out.println(e);
}
Debugging the code (breakpoint in "Scanner sc ..") an exception is launched and the following is printed:
java.io.FileNotFoundException: file.txt (the system can't find the
specified file)
I also tried using "/file.txt" and "//file.txt" but same result.
Thank you in advance for any hint
If you just use new File("pathtofile") that path is relative to your current working directory, which is not at all necessarily where your class files are.
If you are sure that the file is somewhere on your classpath, you could use the following pattern instead:
URL path = ClassLoader.getSystemResource("file.txt");
if(path==null) {
//The file was not found, insert error handling here
}
File f = new File(path.toURI());
The JVM will look for the file in the current working directory.
Where this is depends on your IDE settings (how your program is executed).
To figure out where it expects file.txt to be located, you could do
System.out.println(new File("."));
If it for instance outputs
/some/path/project/build
you should place file.txt in the build directory (or specify the proper path relative to the build directory).
Try:
File f = new File("./build/classes/file.txt");
Use "." to denote the current directory
String path = "./build/classes/file.txt";
File f = new File(path);
File Object loads, looking for match in its current directory.... which is Directly in Your project folder where your class files are loaded not in your source ..... put the file directly in the project folder