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

故事扮演 提交于 2020-01-03 05:04:07

问题


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?


回答1:


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?



来源:https://stackoverflow.com/questions/5608286/runnable-jar-runs-fine-with-java-jar-but-problems-with-double-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!