I'm trying to read and write to a file but I'd like to access that file via Resource.
This is what I do
File f = new File(ClassLoader.getSystemResource("/blah/blah/Properties.prop").toURI()); BufferedReader br = new BufferedReader(new FileReader(f)); String line = br.readLine(); PrintWriter p = new PrintWriter(new File(ClassLoader.getSystemResource("/blah/blah/Properties.prop").toURI()));
but neither seems correct. What is the correct way to do this?
Using Java getResourceAsStream() This is an example of using getResourceAsStream method to read a file from src/main/resources directory. First, we are using the getResourceAsStream method to create an instance of InputStream. Next, we create an instance of InputStreamReader for the input stream.
In Java, we can use getResourceAsStream or getResource to read a file or multiple files from a resources folder or root of the classpath. The getResourceAsStream method returns an InputStream . // the stream holding the file content InputStream is = getClass().
1) click project -> properties -> Build Path -> Source -> Add Folder and select resources folder. 2) create your JAR!
For input, try below:
InputStreamReader isReader = new InputStreamReader( this.getClass().getResourceAsStream(templateName)); BufferedReader br = new BufferedReader(isReader);
or
InputStreamReader isReader = new InputStreamReader( <youclassName>.class.getResourceAsStream(templateName)); BufferedReader br = new BufferedReader(isReader);
For output, try below:
PrintWriter writer = new PrintWriter( new File(this.getClass().getResource(templateName).getPath()));
All solution above show how you can receive access to your resources in build folder. It means that resources have been moved to build directory with .class files.
If you need to write some files into resources for saving them after terminated program, then you will have to describe path starting with root project:
./src/main/resources/foo.ext
This solving generally not recommended but may be necessary in other cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With