[英]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:我正在尝试做一个 web 应用程序,但有一个问题:我不知道如何用 Java 打开一个保存在资源文件夹中的文本文件:
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) (文件words.txt)
As you can see on the image I am trying to access words.txt but it isn't working.正如你在图片上看到的,我试图访问 words.txt 但它不起作用。 Any ideas?
有任何想法吗?
Try this.尝试这个。
InputStream is = getClass().getClassLoader()
.getResourceAsStream("/words.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(is));
For best practice, and avoid these problems, put text file ( words.txt
) to WEB_INF folder (this is secure folder for resources).为了获得最佳实践并避免这些问题,请将文本文件 (
words.txt
) 放入 WEB_INF 文件夹(这是资源的安全文件夹)。 Then:然后:
ServletContext context = getContext();
InputStream resourceContent = context.getResourceAsStream("/WEB-INF/words.txt");
Reference: https://stackoverflow.com/a/4342095/3728901参考: https : //stackoverflow.com/a/4342095/3728901
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();
If you want to access in some other class, like you have a utility package and in that, you have a ReadFileUtil.java class which opens and reads the file, you can do it in the following way:如果您想在其他类中访问,例如您有一个实用程序包,并且其中有一个 ReadFileUtil.java 类可以打开并读取文件,您可以通过以下方式进行:
public class ReadFileUtil {
URL url = ReadFileUtil.class.getResource("/"+yourFileName);
File file = new File(url.getPath());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.