Reputation: 11
I develop web dynamic project in Eclipse. One file, file named 'users.txt' is located under classes folder (WEB-INF/classes/users.txt).
How I can get relative path of this file in class (base class, not servlet class)? I will use that path for append several lines of text.
Christian this is the code that works for reading. Problem is I don't know how to create object for writing (output) in the same file with relative path.
public Products(){
try{
InputStream in = getClass().getClassLoader().getResourceAsStream("products.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
readProducts(br);
in.close();
br.close();
}catch(Exception e){
System.out.println("File doesn't exists");
}
}
public void readProducts(BufferedReader in) throws NumberFormatException, IOException{
String id="";
String name="";
double price=0;
StringTokenizer st;
String line;
while((line=in.readLine())!=null){
st=new StringTokenizer(line,";");
while(st.hasMoreTokens()){
id=st.nextToken();
name=st.nextToken();
price=Double.parseDouble(st.nextToken());
}
products.put(id,new Product(id,name,price));
}
}
Upvotes: 1
Views: 11809
Reputation: 12416
Generally speaking you should not rely on modifying files in your web application directory.
One of the reasons is that servlet container is not obligated to extract your .war
file to the fs, it could, in theory, run your web application from memory. Yeah, Tomcat and most of the containers do unpack .war
but there is nothing in Java EE specs that says that they must do this.
Anyway, if you think that this worth the risk you can use ServletContext.getRealPath to get location of the file inside your webapp directory.
This should look something like this:
myfile
under your webapp root (should be located in the same folder as WEB-INF
in your .war
).do something like this in your servlet (or anywhere where you can access servlet context):
String filePath = getServletContext().getRealPath("myfile");
Note that in order for this to work you should be able to fetch the file with request, like: http://<host>:<port>/<contextPath>/myfile
(see method docs for details)
Upvotes: 2