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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27703508/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 04:53:42  来源:igfitidea点击:

Read file from /src/main/resources/

javaeclipsepathrelative-path

提问by Tr?umerei

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 打开一个保存在资源文件夹中的文本文件:

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)

(文件words.txt)

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

正如你在图片上看到的,我试图访问 words.txt 但它不起作用。有任何想法吗?

回答by Bishan

Try this.

尝试这个。

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

回答by Do Nhu Vy

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

为了获得最佳实践并避免这些问题,请将文本文件 ( words.txt)放入WEB_INF 文件夹(这是资源的安全文件夹)。然后:

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

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

参考:https: //stackoverflow.com/a/4342095/3728901

回答by e18r

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();

回答by Akshay Chopra

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());

    }