1

I learn servlet programming in java, using tomcat 7 as server, eclipse as IDE and ubuntu as OS. I need to open file "xyz.txt" in META-INF folder, but I want to do it independent from working environment (file system, OS, IDE, server, production-development env...). I've been search for hours for answer to this question but no success. I read that I should use code similar to this below, but all of these lines of code give me null (It's in Servlets doGet method, maybe it's not the right place for such code but it's just for learning purposes):

this.getClass().getResource("META-INF/xyz.txt"),
this.getClass().getResource("/META-INF/xyz.txt"),
this.getClass().getResourceAsStream("META-INF/xyz.txt"),
this.getClass().getResourceAsStream("/META-INF/xyz.txt"),
this.getClass().getClassLoader().getResource("META-INF/xyz.txt"),
this.getClass().getClassLoader().getResource("/META-INF/xyz.txt"),
this.getClass().getClassLoader().getResourceAsStream("META-INF/xyz.txt"),
this.getClass().getClassLoader().getResourceAsStream("/META-INF/xyz.txt"),

Edit: Is there a way to have java.io.File object pointing to xyz.txt file?

Marko
  • 1,267
  • 1
  • 16
  • 25

2 Answers2

2

Use a ServletContext method. E.g. getResourceAsStream(). Try the following code inside doGet():

ServletContext context = getServletContext();
InputStream inStream = context.getResourceAsStream("/META-INF/xyz.txt");
Kuba Rakoczy
  • 3,954
  • 2
  • 15
  • 16
  • getResourceAsStream works, but getResource gives me URL in form of jndi:/localhost/projectname/META-INF/xyz.txt which I don't know how to use really. I'm just curious, is there I way to have java.io.File object pointing to xyz.txt? – Marko Dec 14 '14 at 20:19
  • You mean something like: `File f = new File(context.getResource(path).toURI());` ? – Kuba Rakoczy Dec 14 '14 at 20:36
  • If you put the correct path and it isn't really working (I'm unable to test it right now) you should use @Sas solution. – Kuba Rakoczy Dec 14 '14 at 20:53
  • No, it doesn't work. But thank you for your first answer. Yes Sas's answer is what I really wanted. Thank you both. – Marko Dec 14 '14 at 20:53
1

Use context.getRealPath to get absolute path and create a file object to access the file:

File file = new File(getServletContext().getRealPath("META-INF/xyz.txt"));
Sas
  • 2,473
  • 6
  • 30
  • 47