简体   繁体   中英

Need help accessing data file in Jar File

I am having trouble reading a file that is in an exported jar file I had exported from my Eclipse project. I would like to acesss this same file when either running my application on the command line, or when running the same application within Eclipse and have it access the same file via the source hierarchy from within Eclipse (ie not via the Jar File).

In my Java project, I have a folder called: SoundDir, and within it a sound file called: sonar-beep.wav . This is the file I am having trouble accessing.

Here is the line of code I am trying to use to access the sound file:

InputStream input = getClass().getResourceAsStream("SoundDir/sonar-beep.wav");

When I run my program in the Eclipse Debugger, input keeps coming back as Null. I assume it is not finding the file.

Any ideas on what is wrong?

Now, if this did work, I would want to use the inputStream as an argument to the Java SoundPlayer to play the music in this data file. Can I supply "input" directly as the parameter, or do I need a BufferedReader or some other object on top of it?

AudioInputStream audioIn1= AudioSystem.getAudioInputStream(input);

Would appreciate any help on this! New to all these classLoader issues.

Thanks.


Ok, now that this is solved. See solution below from Robert, having same issue with image files. I want my program to be able to locate them, whether the application is running within Eclipse, or on the command line.

Here is the code: ImageIcon imageIcon= new ImageIcon(getImageURL("/ImageAirplanes/AirplaneRtoL.png"));

And here is the method getImageURL:

public URL getImageURL(String imageFilename) {
    URL aURL= null;

    ClassLoader cl = this.getClass().getClassLoader();

    aURL= cl.getResource(imageFilename);

     return aURL;
}

I keep getting a null value for aURL when running the program within Eclipse. And I do have the parent directory of ImageAirplanes (which is "Resources"), added to the Java Build Path for my project.

Any ideas? Thanks.

Where is your SoundDir directory located in the JAR file? Try unpacking the JAR file and checking if you are not sure.

If your SoundDir directory is located in the immediately inside the JAR'd directory, then it is relative to the JAR root directory, and you need to use /SoundDir/sonar-beep.wav - note the leading slash. This makes the path absolute , or relative to root

Without that slash, you are specifying a relative path , which is relative to the classloader - loading a resource that is contained in the same package as the class returned by getClass() .

To understand more deeply, it is helpful to understand File System paths

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM