Read file from /src/main/resources/

2019-01-12 07:53发布

Hello 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?

3条回答
Luminary・发光体
2楼-- · 2019-01-12 07:57

Try this.

InputStream is = getClass().getClassLoader()
                         .getResourceAsStream("/words.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(is));
查看更多
一纸荒年 Trace。
3楼-- · 2019-01-12 08:02

Use this code to find the path to the file you want to open.

import java.net.URL;

[...]

URL url = this.getClass().getResource("/words.txt");
String absoluteDiskPath = url.getPath();
查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-01-12 08:16

For best practice, and avoid these problems, put text file (words.txt) to WEB_INF folder (this is secure folder for resources). Then:

ServletContext context = getContext();
InputStream resourceContent = context.getResourceAsStream("/WEB-INF/words.txt");

Reference: https://stackoverflow.com/a/4342095/3728901

查看更多
登录 后发表回答