Read file from /src/main/resources/
Asked Answered
D

4

8

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?

Dossal answered 30/12, 2014 at 10:15 Comment(2)
/src/main/resources/, though present in your project directory structure, is probably not a part of the Web path.Envision
Thanks for your answer. /src/main/resources/ is not working. How should I change the directory structure?Service
G
10

Try this.

InputStream is = getClass().getClassLoader()
                         .getResourceAsStream("/words.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(is));
Giannini answered 30/12, 2014 at 10:23 Comment(3)
Thread.currentThread().getContextClassLoader() may be a better option, as stated here: #3161191Haslam
Thanks for your answer, but this does not work for me. Still can't find the file.Service
Remove the "/", just: ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream is = classLoader.getResourceAsStream("words.txt");Haslam
S
1

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://mcmap.net/q/88626/-file-path-to-resource-in-our-war-web-inf-folder

Scirrhus answered 30/12, 2014 at 10:31 Comment(3)
Thank you for the answer. Sadly your answer doesn't work for me.Service
@dovy, In this case, you have to maintain two different codes (java standalone, web) just because of the directory issue. I think this is not a good idea.Snapp
what if the file is in the src/main/resources folder in a separate .jar? There is no way to move it to the WEB_INF folder of the webapp module...Stockish
S
0

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();
Skywriting answered 11/9, 2018 at 15:15 Comment(0)
O
0

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

    }
Older answered 30/12, 2019 at 8:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.