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?

Dharman
  • 30,962
  • 25
  • 85
  • 135
Träumerei
  • 81
  • 1
  • 1
  • 2

4 Answers4

10

Try this.

InputStream is = getClass().getClassLoader()
                         .getResourceAsStream("/words.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(is));
Bishan
  • 15,211
  • 52
  • 164
  • 258
  • 1
    ``Thread.currentThread().getContextClassLoader()`` may be a better option, as stated here: http://stackoverflow.com/questions/3160691/how-to-read-properties-file-in-web-application – Baderous Dec 30 '14 at 10:26
  • Thanks for your answer, but this does not work for me. Still can't find the file. – Träumerei Dec 30 '14 at 10:56
  • 2
    Remove the "/", just: ``ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream is = classLoader.getResourceAsStream("words.txt");`` – Baderous Dec 30 '14 at 11:04
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://stackoverflow.com/a/4342095/3728901

Community
  • 1
  • 1
Vy Do
  • 46,709
  • 59
  • 215
  • 313
  • Thank you for the answer. Sadly your answer doesn't work for me. – Träumerei Dec 30 '14 at 10:57
  • @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. – SUNDONG Jan 13 '16 at 07:51
  • 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... – beluchin Sep 08 '16 at 13:45
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();
Cliff
  • 10,586
  • 7
  • 61
  • 102
e18r
  • 7,578
  • 4
  • 45
  • 40
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());

    }
Akshay Chopra
  • 1,035
  • 14
  • 10