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
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.