简体   繁体   中英

FileInputStream look into root of Jar

I have a FileInputStream in a class in the package com.nishu.ld28.utilities, and I want to access sound files in the folder Sounds, which is not in the com.nishu.ld28 package. I specify the path for loading like so:

"sounds/merry_xmas.wav"

And then try to load it like this:

new BufferedInputStream(new FileInputStream(path))

When I export the jar, the command line prompt that I run it through says it can't find the file. I know how to access the files when I am running the program in Eclipse, but I can't figure out how to point the FileInputStream to the Sounds folder when I export it.

Edit: As requested, here's my code:

public void loadSound(String path)  {
    WaveData data = null;
    data = WaveData.create(GameSound.class.getClassLoader().getResourceAsStream(path));
    int buffer = alGenBuffers();
    alBufferData(buffer, data.format, data.data, data.samplerate);
    data.dispose();
    source = alGenSources();
    alSourcei(source, AL_BUFFER, buffer);
}

WaveData accepts an InputStream or other types of IO.

You don't need a FileInputStream , because you aren't reading from the filesystem. Use the InputStream returned by ClassLoader.getResourceAsStream(String res) or Class.getResourceAsStream(String res) . So either

in = ClassLoader.getResourceAsStream("sounds/merry_xmas.wav");

or

in = getClass().getResourceAsStream("/sounds/merry_xmas.wav");

Note the leading slash in the second example.

I would put the com.nishu.ld28.utilities in the same package of your class , let's call it MyClass .

Your package:

在此输入图像描述

Your code:

package com.nishu.ld28.utilities;

import java.io.InputStream;

public class MyClass {

   public static void main(String[] args) {
      InputStream is = MyClass.class.getResourceAsStream("sound/merry_xmas.wav");

      System.out.format("is is null ? => %s", is==null);
   }
}

Output

is is null ? => false

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