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:
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?
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().
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 .
Try this.
InputStream is = getClass().getClassLoader()
.getResourceAsStream("/words.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(is));
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