2

When I run my main method it creates src/main/resources/sample.txt file and then read the content of it. Whenever I run the code it gives java.lang.NullPointerException, when it comes to read src/main/resources/sample.txt. However when I refresh the project, it reads the sample.txt but not the new content, it reads the old content. It's seems like I need to refresh java project in eclipse before read the text file. Is there a way to refresh src/main/resources while executing?

1 Answer 1

3

If you are able to write that file, then you should be able to read it.

My guess is you are writing it using a file path src/main/resources, but you are reading it using ClassLoader.getResource, which reads from the classpath target/classes.

When you refresh the project and eclipse builds it, the source files in src/main/resources get copied to target/classes, making them available in the class path as resources.

I would advise against writing anything in src/main/resources, since that only works if you are executing the project from the project directory.

Typically, a ClassLoader's class path is set up during program start. Depending on it's caching implementation, it is usually not possible for the classloader to pick up on changes in files in the classpath. You would need to create a new ClassLoader and discard the old one, but this is far too complex for this situation.

To read the file, use code similar to how you wrote the file: If you used FileWriter, use FileReader; if you used FileOutputStream, use FileInputstream, etc.

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

3 Comments

Yeah you are exactly right.This is how I read the text file TestClass.class.getClassLoader().getResource("sample.txt"). Is there another way of reading "/anypath/sample.txt" from TestClass.class?
Answer updated. I'm not sure if this is exactly what you're looking for; it's a bit odd to write a file and then read it, since you could keep the contents in memory. So if I'm off, could you provide some code or some more details?
Well I found a way File file= new File("/home/anypath/sample.txt");

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.