Runnable jar运行良好的java -jar,但双击的问题 [英] Runnable jar runs fine with java -jar, but problems with double-click

查看:107
本文介绍了Runnable jar运行良好的java -jar,但双击的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是eclipse IDE,我使用'export-> Runnable Jar'导出了我的项目。在我的代码中,我已经使用

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

及以后

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

,然后使用

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

现在,当我将map01.txt打包到jar中并双击它运行,但找不到map01.txt。当我使用java -jar,它运行,但仍然找不到地图。
当我将map01.txt放在与jar文件相同的目录中,但实际上不在jar中,然后双击它,它运行,但找不到地图。如果我使用java -jar运行它,它运行并加载地图。这个问题的原因是什么?我该怎么解决?而map01.txt是唯一不起作用的资源。我加载了许多放在jar文件中的图像,它们都加载并显示正常。对于图像我使用

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

为什么他们工作不是我的地图?如何解决这个问题,所以我可以将所有资源打包到一个jar中,然后双击它运行?

解决方案

你说新的File(map1url.getFile()),你最后使用一个java.io.File来引用当前目录下的一个文件。如果文件实际上位于进程的当前目录中(如果shell中当前目录下的文件,并且使用java -jar,则会发生这种情况),否则将不会。 p>

为什么不使用getResource()。openStream()来读取地图文件?


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?

这篇关于Runnable jar运行良好的java -jar,但双击的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆