简体   繁体   English

如何在Java文件中指定相对文件路径,以便在将文件放入jar文件后它仍然可以工作?

[英]How to specify relative file path in Java file so that it can still work after the file is put in jar file?

Suppose I have a Java class that needs to access a file with absolute path /home/gem/projects/bar/resources/test.csv: 假设我有一个需要使用绝对路径/home/gem/projects/bar/resources/test.csv访问文件的Java类:

package com.example
class Foo {
String filePath = ????? // path to test.csv
String lines = FileInputStream(new File(filePath).readAllLines();

}

Where the path to Foo.java is /home/gem/projects/bar/src/com/example. Foo.java的路径是/ home / gem / projects / bar / src / com / example。

Of course I cannot specify absolute path to the resource file. 当然我不能指定资源文件的绝对路径。 This is because jar file will be distributed as library for any clients to use in their own environments. 这是因为jar文件将作为库分发,供任何客户端在自己的环境中使用。

Assume the resource file like test.csv is always in the same path relative to project root. 假设像test.csv这样的资源文件总是在相对于项目根目录的相同路径中。 When a jar is created containing Foo.class, this jar also contains test.csv in the same relative path ( relative to project root). 当创建包含Foo.class的jar时,此jar还包含相同路径(相对于项目根目录)的test.csv。

What is the way to specify relative path that would work no matter where the project bar is moved to? 无论项目栏移动到何处,指定相对路径的方法是什么? Also how can I create a jar file (which can be in any location) so that the path to the resource file test.csv would still be correct. 另外,我如何创建一个jar文件(可以在任何位置),以便资源文件test.csv的路径仍然正确。

To keep things simple, I have used invalid Java API ( readAllLines() which reads all the lines and return a string containing entire file content. Also not using try/catch). 为了简单起见,我使用了无效的Java API(readAllLines(),它读取所有行并返回包含整个文件内容的字符串。也不使用try / catch)。

Assume csv file can be read as well as written to. 假设csv文件既可以读取也可以写入。

I hope this makes it clear now. 我希望现在能说清楚。

Put the test.csv file into the src folder and use this: test.csv文件放入src文件夹并使用:

Foo.class.getResourceAsStream("/test.csv")

To get an InputStream for the file. 获取文件的InputStream This will work wherever the project is moved, including packaged as a JAR file. 这将在项目移动的任何位置工作,包括打包为JAR文件。

Example: 例:

ProjectX\\src\\Test.java projectX创建的\\ src \\ Test.java

ProjectX\\resources\\config.properties projectX创建\\资源\\ config.properties

If you have the above structure and you want to use your config.properties file, this is how you do it: 如果您具有上述结构并且想要使用config.properties文件,则执行此操作:

InputStream input = new FileInputStream("./resources/config.projects"); InputStream input = new FileInputStream(“./ resources / config.projects”);

In this example you don't have to worry about packaging your source into jar file. 在此示例中,您不必担心将源打包到jar文件中。 You can still modify your resources folder anytime. 您仍然可以随时修改资源文件夹。

使用getResource()如图所示这里

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

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