I am using the JLayer(JZoom) API to play an mp3 file in my java application.
This is the code I implemented, I created a method and then call it later which works fine:
public void playMusic() {
try{
FileInputStream fis = new FileInputStream("myfilepath/file.mp3");
Player playMP3 = new Player(fis);
playMP3.play();
}
catch(Exception exc){
exc.printStackTrace();
System.out.println("Failed to play the file.");
}
}
When I export a runnable JAR file, the file is not included. I have also included the MP3 file in an assets folder located in the SRC folder of my application.
What can I do different in order to include the MP3 file when exporting to a runnable JAR file ?
You cannot use a FileInputStream to load a resource from a JAR file, because a resource in a JAR file is not a file.
Use:
InputStream in = YourClassName.class.getClassLoader().getResourceAsStream("myfilepath/file.mp3");
assuming the path inside the JAR file is myfilepath/file.mp3, and YourClassName is the name of any class inside the JAR file.
Related
I'm using Play 2.5 and I have written a code, in Java, to create a file in /app/public folder, I parametrized the path in application.conf. After that I created a dist file and when I tried to call that method from my dist file, the file is not getting generated in /public folder. Is it not able to detect the path?
file.create{
path = "public/"
}
Edit: Java Code -
String filePath = conf.getString("file.create.path") + "Excel_file.xlsx";
FileOutputStream fos = new FileOutputStream(filePath);
Whenever I open my .jar file, the sound will not work unless the files are in a folder titled "res" in the same directory as the .jar file. Now it will now work regardless of where the res folder is
Here's my code
try {
InputStream defaultSound = Game.class.getResourceAsStream("/TrailsGameMusic.wav");
// getClass().getSy.getResource("/images/ads/WindowsNavigationStart.wav");
System.out.println("defaultSound " + defaultSound); // check the URL!
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(defaultSound);
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.loop(Clip.LOOP_CONTINUOUSLY);
} catch (Exception ex) {
ex.printStackTrace();
}
It's probably a problem with absolute path:
If you declare it like that: "/res/TrailsGameMusic.wav", you are referring to absolute path - it works. If you will write only "TrailsGameMusic.wav", it will be a relative path - it will not work.
You can configure your resources using for example this link:
How do I add a resources folder to my Java project in eclipse
So I've created a game, runs perfectly in eclipse--all of the images load and it reads properly from a text file. The text file provides level info.
This is where my problem comes in.
I exported it all to an executable .jar file, and it found all of the images. But it did not find the .txt file. Where does the .txt file need to be for it to be found?
try{
controlBoard = new Scanner(new FileInputStream("lvl1.txt"));
}catch(Exception e){
gb.error = true;
}
You should not access that file using FileInputStream. Get an InputStream using the class loader and getResourceAsStream(). It'll find it in the JAR.
I put some .txt files under the src folder (in the resources folder).
But I can't create a valid File at runtime from this resource.
String path = this.getClass().getResource("/resources/file.txt").getFile();
File file = new File(path);
if (!file.exists()) {
}
I run my program from eclipse. I didn't put in classpath anything.
I want my text files to be embedded into the .jar file, when I run my app I want to grab those files and copy them into some location.
UPDATE
if I do InputStream is = getClass().getResourceAsStream("/resources/file.txt");
I get the stream!!
As you already discovered yourself soon after posting your question, this works:
InputStream is = getClass().getResourceAsStream("/resources/file.txt");
The reason this works, while your original code doesn't, is because a "file" inside in a zip file (a jar file is a zip file) is not a real file until it has been extracted. But extracting the file is what you are trying to do, so at that point in your program, it's not a real file. So this question is an X-Y problem: you wanted to create a File object, but that wasn't possible - you needed to refer back to what you were originally trying to do, which was read from the zip entry.
You said that you are using eclipse, and that you dragged and dropped your text files into the "src" package. "src" is not a package. It is simply a file system directory. By default in a Java project in eclipse all your source code is stored in a directory called "src" and all your .class files are stored in a directory called "bin". getClass().getResource() resolves to the location of your .class files. You must move the text files into the "bin" directory.
What package is your class in?
I wrote very similar code to yours in the default package and ran it in eclipse.
import java.io.File;
public class ResourceTest {
public static void main(String[] args) {
ResourceTest rt = new ResourceTest();
rt.openFile();
}
public void openFile() {
String path = this.getClass().getResource("/resources/file.txt").getFile();
File file = new File(path);
System.out.println(path);
System.out.println(file.getAbsolutePath());
System.out.println(file.exists());
}
}
I see this output:
/C:/Users/rab29/Documents/eclipse/Overflow/bin/resources/file.txt
C:\Users\rab29\Documents\eclipse\Overflow\bin\resources\file.txt
true
I have a nasty problem referencing resources when using a Maven project and Jar files...
I have all my resources in a dedicated folder /src/main/resources which is part of the build path in Eclipse. Files are referenced using
getClass().getResource("/filename.txt")
This works fine in Eclipse but fails in the Jar file - there the resources are located in a folder directly below the jar's root...
Does anyone know a 'best practice' to reference a file both in the JAR and (!) in Eclipse?
Edit:
The problem is that while the resources actually are located in the JAR in a folder "resources" at the top level, the above method fails to find the file...
Once you pack the JAR, your resource files are not files any more, but stream, so getResource will not work!
Use getResourceAsStream.
To get the "file" content, use https://commons.apache.org/proper/commons-io/javadocs/api-release/org/apache/commons/io/IOUtils.html:
static public String getFile(String fileName)
{
//Get file from resources folder
ClassLoader classLoader = (new A_CLASS()).getClass().getClassLoader();
InputStream stream = classLoader.getResourceAsStream(fileName);
try
{
if (stream == null)
{
throw new Exception("Cannot find file " + fileName);
}
return IOUtils.toString(stream);
}
catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
return null;
}
I had a similar problem.
After a full day of trying every combination and debugging I tried getClass().getResourceAsStream("resources/filename.txt") and got it to work finally.
Nothing else helped.
The contents of Maven resource folders are copied to target/classes and from there to the root of the resulting Jar file. That is the expected behaviour.
What I don't understand is what the problem is in your scenario. Referencing a Resource through getClass().getResource("/filename.txt") starts at the root of the classpath, whether that (or an element of it) is target/classes or the JAR's root. The only possible error I see is that you are using the wrong ClassLoader.
Make sure that the class that uses the resource is in the same artifact (JAR) as the resource and do ThatClass.class.getResource("/path/with/slash") or ThatClass.class.getClassLoader().getResource("path/without/slash").
But apart from that: if it isn't working, you are probably doing something wrong somewhere in the build process. Can you verify that the resource is in the JAR?
If you add the resources directory in the jar file (so it is under the /resources folder in the jar, and if /src/main is in your build path in eclipse, then you should be able to reference your file as:
getClass().getResource("/resources/filename.txt");
Which should work in both environments.
The problem is that within the IDE the getClass().getResource("Path"); String is not CASE SENSITIVE when accessing a file but when running from a jar it is. Check your Capitalisation on directory compared to file. It does work. Also if you try new File(getClass().getResource("Path"); the file won't be readable outside IDE.
Maybe this method can help for some situations.
public static File getResourceFile(String relativePath)
{
File file = null;
URL location = <Class>.class.getProtectionDomain().getCodeSource().getLocation();
String codeLocation = location.toString();
try{
if (codeLocation.endsWith(".jar"){
//Call from jar
Path path = Paths.get(location.toURI()).resolve("../classes/" + relativePath).normalize();
file = path.toFile();
}else{
//Call from IDE
file = new File(<Class>.class.getClassLoader().getResource(relativePath).getPath());
}
}catch(URISyntaxException ex){
ex.printStackTrace();
}
return file;
}
Just copy the file to a temporary directory.
String tempDir = System.getProperty("java.io.tmpdir");
File file = new File(tempDir.getAbsolutePath(), "filename.txt");
if (!file.exists()) {
InputStream is = (getClass().getResourceAsStream("/filename.txt"));
Files.copy(is, file.getAbsoluteFile().toPath());
}