8803286 8803286 - 5 months ago 14
Java Question

Is there a way to get a file from res folder with ClassLoader and getClass() method

I have the loadImage function for getting images. It only does not work when I am trying to get the file from the getFile() function.

public BufferedImage loadImage(String img) {
BufferedImage bimg = null;
try {
bimg = ImageIO.read(new File("res/" + img));
} catch (Exception e1) {
try {
bimg = ImageIO.read(ClassLoader.getSystemResource("res/" + img));
} catch (Exception e2) {
try {
bimg = ImageIO.read(getClass().getResource("res/" + img));
} catch (Exception e3) {
System.out.println("Cannot load image: " + img);
}
}
}
return bimg;
}


I have tried using the following function:

public File getFile(String file) {
File f = null;
try {
f = new File("res/" + file);
} catch (Exception e1) {
try {
f = new File(ClassLoader.getSystemResource("res/" + file).getFile());
} catch (Exception e2) {
try {
f = new File(getClass().getResource("res/" + file).getFile());
} catch (Exception e3) {
System.out.println("Cannot load File: " + file);
}
}
}
return f;
}


These functions are in a jar lib and my other project want to get a file from the jar lib.

This is in my project trying to get config.cfg file from the jar lib

File file = files.getFile("config.cfg");


I have opened the jar and checked, if that the file exists inside the jar.

Any edits to improve my question are welcome, I don't speak English very well.

Answer

You can use the Class.getResourceAsStream(String name). For example, if you have "/data/config.cfg" in the jar file, then you can open that file for reading using the following line:

InputStream is = this.getClass().getResourceAsStream("/data/config.cfg");