Runnable jar runs fine with java -jar, but problem

2019-06-11 13:51发布

问题:

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?