从/ src / main / resources /读取文件

问题描述 投票:4回答:3

您好我正在尝试执行Web应用程序并遇到问题:我不知道如何使用保存在资源文件夹中的Java打开文本文件:

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

(文件words.txt)

正如你在图像上看到的那样,我试图访问words.txt,但它无法正常工作。有任何想法吗?

java eclipse web path relative
3个回答
6
投票

试试这个。

InputStream is = getClass().getClassLoader()
                         .getResourceAsStream("/words.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(is));

0
投票

为了最佳实践,并避免这些问题,将文本文件(qazxsw pi)放到WEB INF文件夹(这是资源的安全文件夹)。然后:

words.txt

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


0
投票

使用此代码查找要打开的文件的路径。

https://stackoverflow.com/a/4342095/3728901
© www.soinside.com 2019 - 2024. All rights reserved.