简体   繁体   English

Java NetBeans 中的相对路径

[英]Java relative path in NetBeans

I am developing a NetBeans module where I have a Java package called test and another package called test.templates .我正在开发一个 NetBeans 模块,其中我有一个 Java package 称为test和另一个 ZEFE90A8E604A7C840D8Z 称为test.templates I want to read a text file which is in the test.templates package from a Java file in the test package.我想从测试 package 中的 Java 文件中读取test.templates package 中的文本文件。 I tried in several ways, but it gives a FileNotFoundException exception:我尝试了几种方法,但它给出了FileNotFoundException异常:

BufferedReader br = new BufferedReader(new FileReader("templates/test.txt"));
BufferedReader br = new BufferedReader(new FileReader("/test/templates/test.txt"));
BufferedReader br = new BufferedReader(new FileReader("src/test/templates/test.txt"));

But none of these worked.. I want to use the relative path, not the absolute path.但是这些都不起作用..我想使用相对路径,而不是绝对路径。 What should I do?我应该怎么办?

You should note somethings about relative path (Netbeans):你应该注意一些关于相对路径(Netbeans)的事情:

+ File: Default is project folder, means outside of src folder. + 文件:默认是项目文件夹,表示在src文件夹之外。
If you save to test.txt , it will generate: project/test.txt .如果保存到test.txt ,它将生成: project/test.txt
If you save to data/test.txt , ... project/data/test.txt如果保存到data/test.txt ,... project/data/test.txt
So if you want to load file, you just do it conversely.因此,如果要加载文件,则相反。 Like this, you should put your files in project/data/filename.txt.像这样,您应该将文件放在 project/data/filename.txt 中。 Then when code, you get path: data/filename.txt .然后在编码时,你会得到 path: data/filename.txt

+ ImageIcon: I will share later if can. + ImageIcon:如果可以,我稍后会分享。
+ Image(SplashScreen): I will share later. + 图片(SplashScreen):我稍后会分享。

You will want to use getResource or getResourceAsStream .您将需要使用getResourcegetResourceAsStream

Example on java2s.com: java2s.com 上的示例:

http://www.java2s.com/Code/Java/Development-Class/Loadresourcefilerelativetotheclasslocation.htm http://www.java2s.com/Code/Java/Development-Class/Loadresourcefilerelativetotheclasslocation.htm

getResource() returns a URL, so to extract the filename, you can try calling getFile() . getResource()返回一个 URL,因此要提取文件名,您可以尝试调用getFile()

The filepath you pass to getResource will be based on your netbeans package.您传递给 getResource 的文件路径将基于您的 netbeans package。 Use a leading slash to denote the root of the classpath.使用前导斜杠表示类路径的根。

Example:例子:

getResource(/db_files/table.csv).getFile()
try
{
BufferedReader br = new BufferedReader(new FileReader(getClass().getResource("/test/templates/test.txt").toString().substring(6)));
}
catch(Exception ee)
{
JOptionPane.showMessageDialog(this, ee);   
}

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

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