简体   繁体   English

将Eclipse Java项目导出到可执行jar时,如何调整相对和绝对路径?

[英]How to adjust relative & absolute paths when exporting eclipse java project to executable jar?

Ok so I have a project in eclipse called SWT. 好的,所以我在Eclipse中有一个名为SWT的项目。 In one of the classes in this project there is a code: 在该项目的一个类中,有一个代码:

public static String rpath = "..\\SWT\\src\\data.txt";
public static String path = new File(rpath).getAbsolutePath();

If I compile and run my project in eclipse, my program is able to find data.txt and use it as input, which is the file's intended purpose. 如果我在eclipse中编译并运行项目,则我的程序能够找到data.txt并将其用作输入,这是文件的预期目的。

I then export this project to an executable jar file, open the command prompt and enter java -jar SWT.jar. 然后,我将此项目导出到可执行的jar文件,打开命令提示符,然后输入java -jar SWT.jar。 the program opens but in the command prompt, there is the following error: 程序打开,但是在命令提示符下,出现以下错误:

java.io.FileNotFoundException: C:\\Users\\Yoshikawa\\workspace\\SWT\\..\\data.txt (The system cannot find the file specified)

My question: 我的问题:

How can I modify my code prior to exporting it to an executable jar, so that I can make my executable jar able to find the data.txt? 在将代码导出到可执行jar之前,该如何修改代码,以便使可执行jar能够找到data.txt? By the way, my executable jar contains data.txt already, but is not able to use the relative path specified above to find its exact location, which I find very very odd. 顺便说一句,我的可执行jar已经包含data.txt,但是无法使用上面指定的相对路径来找到其确切位置,我觉得这很奇怪。

There will be no src directory in your jar file. 您的jar文件中将没有src目录。 Only the package names and class files. 仅软件包名称和类文件。

Try this: 尝试这个:

URL url = ClassLoader.getSystemResource("/data.txt");
File file = new File(url.toURI());

More info here . 更多信息在这里

You can put the file, data.txt, at some package and then use a class from this package to do this: 您可以将文件data.txt放在某个包中,然后使用该包中的类来执行此操作:

URL url = ClassFromSamePackageOfFile.class.getResource( "data.txt" );

File f;
try {
  f = new File(url.toURI());
} catch(URISyntaxException e) {
  f = new File(url.getPath());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM