servlets - How can I get path of resource under WEB-INF/class folder (java ee web dynamic project) -


i develop web dynamic project in eclipse. 1 file, file named 'users.txt' located under classes folder (web-inf/classes/users.txt).

how can relative path of file in class (base class, not servlet class)? use path append several lines of text.

christian code works reading. problem don't know how create object writing (output) in same file 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));         }     } 

generally speaking should not rely on modifying files in web application directory.

one of reasons servlet container not obligated extract .war file fs, could, in theory, run web application memory. yeah, tomcat , of containers unpack .war there nothing in java ee specs says must this.

anyway, if think worth risk can use servletcontext.getrealpath location of file inside webapp directory.

this should this:

  1. create file myfile under webapp root (should located in same folder web-inf in .war).
  2. do in servlet (or anywhere can access servlet context):

    string filepath = getservletcontext().getrealpath("myfile");

note in order work should able fetch file request, like: http://<host>:<port>/<contextpath>/myfile (see method docs details)


Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -