joey942 joey942 - 4 months ago 11
Java Question

File Path Changing on Export

I'm currently trying to develop a game, and the file path is changing when I export it.

Here is the code:

package random;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;
import javax.swing.JFrame;

public class Troll extends JFrame{
/**
*
*/
private static final long serialVersionUID = 4176461585360667597L;
public static BufferedImage img;
public static void main(String[] args){
File f = new File("troll.png");
try{
if(f.exists()){
System.out.println("ITS THERE! :D");
img = ImageIO.read(f);
} else {
System.out.println("DOESNT EXIST, REAL PATH IS: " + f.getAbsolutePath() );
}
}catch(Exception e){
e.printStackTrace();
}

new Troll();

}
public Troll(){
init();
}
public void init(){
setSize(1200,800);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
public void paint(Graphics g){
g.drawImage(img, 500, 350, this);
}
}


When I run it through Eclipse ( The IDE I'm using ), it's running fine and it's showing the image. When I export it as a jar and convert it to an exe using Jar2Exe Software, the image does not appear and in the console it says that the absolute path for the image is on my Desktop. But when I open the exe using 7-Zip, the picture is in the exe.

How can I export it so that when the user runs it, the program can find the file path and show the image, instead of it thinking that it's on my desktop?

Answer

I hope this is not a troll (lol)

img = ImageIO.read(this.getClass().getResource("/troll.jpg"));

You are in a jar, there is no resource file.


See that link as well: http://www.jar2exe.com/createdexe/integrate/protect

Thread.currentThread().getContextClassLoader().getResource("hello/yes.gif");
Comments