Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read file from /src/main/resources/

I am trying to do a web application and have a problem: I don't know how to open a text file with Java that is saved in the resource folder:

text file saved in the resource folder

 String relativeWebPath ="/src/main/resources/words.txt";  //Import der des Textdoumentes
 String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
 File f = new File(absoluteDiskPath);

(The file words.txt)

As you can see on the image I am trying to access words.txt but it isn't working. Any ideas?

like image 333
Träumerei Avatar asked Dec 30 '14 10:12

Träumerei


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 file in resources folder?

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 view the resources folder in a jar file?

This works when running inside and outside of a Jar file. PathMatchingResourcePatternResolver r = new PathMatchingResourcePatternResolver(); Resource[] resources = r. getResources("/myfolder/*"); Then you can access the data using getInputStream and the filename from getFilename .


1 Answers

Try this.

InputStream is = getClass().getClassLoader()
                         .getResourceAsStream("/words.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(is));
like image 109
Bishan Avatar answered Oct 08 '22 12:10

Bishan