Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read and Write to Java file via Resource

Tags:

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?

like image 297
CodeGuy Avatar asked Oct 21 '12 18:10

CodeGuy


People also ask

How do I read a file from src main resources?

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.

How do I read a resource folder in Java 8?

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

How do I add a resource file to a jar file?

1) click project -> properties -> Build Path -> Source -> Add Folder and select resources folder. 2) create your JAR!


2 Answers

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())); 
like image 168
Yogendra Singh Avatar answered Dec 12 '22 10:12

Yogendra Singh


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.

like image 24
Dmytro Melnychuk Avatar answered Dec 12 '22 11:12

Dmytro Melnychuk