How to open file in META-INF independent of environment

1.4k views Asked by At

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?

2

There are 2 answers

0
Sas On BEST ANSWER

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"));
4
Kuba Rakoczy On

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

ServletContext context = getServletContext();
InputStream inStream = context.getResourceAsStream("/META-INF/xyz.txt");