0

I originally had my .mid file in the project directory and I had got it like this:

 File file = new File("hmr.mid");

It all worked fine, then I tried to export it to a runnable .jar, because than I had NullPointerException when I tried to access the file later.

I have read that I should add the resource to the package, so I did this:

http://kepfeltoltes.hu/140326/115027543proj_www.kepfeltoltes.hu_.png

Since than, I have did a ton of googling, SOF search, looked at a ton of examples (and I think most of people are getting it wrong, e.g. use absolute path), read articles like this:

http://www.thinkplexx.com/learn/howto/java/system/java-resource-loading-explained-absolute-and-relative-names-difference-between-classloader-and-class-resource-loading

but nothing ever worked. I get a NullPointerException just when I export to .jar, but even when I simply run it.

Here is my resource loader with some residue of my attempts. It works fine with images.

import java.awt.Image;
import java.awt.Toolkit;
import java.io.File;
import java.io.InputStream;
import java.net.URL;




public class ResourceLoader {

static ResourceLoader rl = new ResourceLoader();

public static Image getImage(String filename)
{
    return Toolkit.getDefaultToolkit().getImage(rl.getClass().getResource(filename));
}

public static File getFile(String filename)
{
    //InputStream is = rl.getClass().getResourceAsStream("hmr.mid");
    //URL url = Thread.currentThread().getContextClassLoader().getResource("hmr.mid");
    //File file = new File(url.toString());
    //url = File.class.getClassLoader().getResource("/Users/peti/Documents/workspace/java_workspace/BluesBox_v0_21/200_Stlye/resources/hmr.mid");

    //File file = new File(url.getFile());
    //File file = new File("/Users/peti/Documents/workspace/java_workspace/BluesBox_v0_21/200_Stlye/resources/hmr.mid");
    //File file = new File("src/200_Stlye/resources/hmr.mid");
    File file = new File("hmr.mid");

    return file;
}

}

1 Answers1

1

You should use relative path to your resource when using getClass().getResource()

For example "/hmr.mid"

Just be sure that you fill is in classpath in this case.