开发者

Java relative path in NetBeans

I am developing a NetBeans module where I have a Java package called testand another package called tes开发者_StackOverflow社区t.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?


You will want to use getResource or getResourceAsStream.

Example on java2s.com:

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


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() returns a URL, so to extract the filename, you can try calling getFile().

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:

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);   
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜