4

I am developing a NetBeans module where I have a Java package called testand 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?

4 Answers 4

4

You will want to use getResource or getResourceAsStream.

Example on java2s.com:

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

Sign up to request clarification or add additional context in comments.

Comments

3

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.

1 Comment

I'm not sure about this answer :v
1

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()

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.