开发者

Runnable jar runs fine with java -jar, but problems with double-click

I am using the eclipse IDE and I just exported my project using 'export->Runnable Jar'. In my code, I have loaded a map using

URL map1url = this.getClass().getResource("map01.txt");

and later

inputmap = new File(map1url.getFile());

and then scanned its data using

Scanner sc = null;
    try {
        sc = new Scanner(inputmap);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

Now, when I package the map01.txt into the jar, and double click it, it runs, but can't find the map01.txt. When I use java -jar, it runs, but still can't find the map. When I place map01.txt in the same directory as the jar file, but not actually in the jar, and then double-click it, it runs, but doesn't find the map. If I run it using java -jar it runs and loads the map. What is the cause of this problem? How can I fix it? And the map01.txt is the only resource that doesn't work. I have loaded many images that are placed into the jar file, and they all load and display fine. For the images I use

URL url = this.getClass().getResource("myImage.gif");
    try {
        BufferedImage myImage = ImageIO.read(url);
    } catch (IOException e) {
    }    

Why do they work and not my map? How can I fix this 开发者_高级运维so I can package ALL my resources into one jar and then double-click it to run?


When you say "new File(map1url.getFile())", you're ending up with a java.io.File that refers to a file in the current directory. If the file actually is in the current directory of the process (which will happen if the file in in the current directory of your shell and you use "java -jar", then this will work; otherwise, it won't.

Why not just use getResource().openStream() to read the map file?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜