简体   繁体   中英

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:

保存在资源文件夹中的文本文件

 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?

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). Then:

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

Reference: 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:

public class ReadFileUtil {

        URL url = ReadFileUtil.class.getResource("/"+yourFileName);
        File file = new File(url.getPath());

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM