NetBeans 中的 Java 相对路径
我正在开发一个 NetBeans 模块,其中有一个名为 test
的 Java 包和另一个名为 test.templates
的包。我想从测试包中的 Java 文件读取 test.templates 包中的文本文件。我尝试了多种方法,但它给出了 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"));
但这些都不起作用..我想使用相对路径,而不是绝对路径。我应该怎么办?
I am developing a NetBeans module where I have a Java package called test
and another package called test.templates
. I want to read a text file which is in the test.templates
package from a Java file in the test package. I tried in several ways, but it gives a FileNotFoundException
exception:
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您将需要使用
getResource
或getResourceAsStream
。java2s.com 上的示例:
http://www.java2s.com/Code /Java/Development-Class/Loadresourcefilerelativetotheclasslocation.htm
You will want to use
getResource
orgetResourceAsStream
.Example on java2s.com:
http://www.java2s.com/Code/Java/Development-Class/Loadresourcefilerelativetotheclasslocation.htm
您应该注意有关相对路径(Netbeans)的一些信息:
+ 文件:默认为项目文件夹,即在
src
文件夹之外。如果保存到
test.txt
,它将生成:project/test.txt
。如果保存到
data/test.txt
,...project/data/test.txt
所以如果你想加载文件,你只需执行相反的操作即可。像这样,您应该将文件放在project/data/filename.txt 中。然后在编码时,您将获得路径:
data/filename.txt
。+ ImageIcon:如果可以的话我稍后会分享。
+ 图片(SplashScreen):我稍后会分享。
You should note somethings about relative path (Netbeans):
+ File: Default is project folder, means outside of
src
folder.If you save to
test.txt
, it will generate:project/test.txt
.If you save to
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. Then when code, you get path:
data/filename.txt
.+ ImageIcon: I will share later if can.
+ Image(SplashScreen): I will share later.
getResource()
返回一个 URL,因此要提取文件名,您可以尝试调用getFile()
。您传递给 getResource 的文件路径将基于您的 netbeans 包。使用前导斜杠表示类路径的根。
例子:
getResource()
returns a URL, so to extract the filename, you can try callinggetFile()
.The filepath you pass to getResource will be based on your netbeans package. Use a leading slash to denote the root of the classpath.
Example: