I am creating a desktop 2D Game and I have a problem with the executable .jar . In Eclipse everything works fine but when I generate the jar and execute it it won’t load the files(files are images converted into arrays of bytes).the files are located in a folder named “Graphics” with the code below java finds his path to the .jar file and add “Graphics\” to his URL so it can load the files from the Graphics folder.Graphics folder and the the executable .jar are in the same folder.
public class Imageloader {
public BufferedImage loadimg(String graf) throws IOException{
URL jarLocation = Imageloader.class.getProtectionDomain().getCodeSource().getLocation();
String pathg = jarLocation.toString();
System.out.println(pathg);
while(pathg.indexOf("/")!=-1){
pathg=pathg.replace("/", "\\" );
}
pathg=pathg.replace("file:","");
pathg=pathg.substring(1, pathg.length());
String gr="Graphics\\";
System.out.println(pathg+gr+graf);
Path path = Paths.get(pathg+gr+graf);
byte[] data = Files.readAllBytes(path);
InputStream in = new ByteArrayInputStream(data);
BufferedImage bImageFromConvert = ImageIO.read(in);
return bImageFromConvert;
}
}
I have replaced “/” with “\” and deleted the String “file:” and the first character of the String pathg witch is “” so path.get() can work fine .as i mentioned In Eclipse everything works perfectly and loads every single file, this is what the console shows :
C:\workspace\SpaceGameTest\bin\Graphics\menu.amg
C:\workspace\SpaceGameTest\bin\Graphics\spacegamespritesheet.amg
C:\workspace\SpaceGameTest\bin\Graphics\playersprites.amg
C:\workspace\SpaceGameTest\bin\Graphics\background.amg
C:\workspace\SpaceGameTest\bin\Graphics\enemy.amg
this is whats in the Main class :
Imageloader imgload =new Imageloader();
try{
menu=imgload.loadimg("menu.amg");
spritesheet=imgload.loadimg("spacegamespritesheet.amg");
playerspt=imgload.loadimg("playersprites.amg");
Background=imgload.loadimg("background.amg");
enemy=imgload.loadimg("enemy.amg");
}catch(IOException e) {
e.printStackTrace();
}
.amg is just a random format but its basically file of byte[]
I don’t want to load the files as a resources
EDITED
After compiling the .jar using windows cmd it seems like the application is not getting the path of the .jar file while in Eclipse it is getting the complete path
http://img15.hostingpics.net/pics/778776javahh.jpg
so whats wrong with
URL jarLocation = Imageloader.class.getProtectionDomain().getCodeSource().getLocation();