1

I'm trying to open a file but the current CWD is wrong. I've tried to open class file from /ROOT/app/WEB-INF/classes/pl/jcubic/Service.class

but current working directory using:

    File root = new File(".");
    root.getAbsolutePath();

Return /var/lib/tomcat7/. path, how can I get the app directory from a servlet (I want my code to work even if I change the name or run on Windows machine).

jcubic
  • 61,973
  • 54
  • 229
  • 402
  • 1
    Do you want to read the file from your web application which exists in your web application ? – Makky Dec 01 '13 at 15:42
  • Are you trying to open a file that's contained in your servlet? If so, don't use the `File` API; there's no requirement at all that the container unpack your servlet. Use the `getResource` methods instead. – chrylis -cautiouslyoptimistic- Dec 01 '13 at 15:42
  • @Makky yes, but I don't use WAR file only symlink to my app in `webapps` directory. I recompile one file (load it using my own class loader) without the need for deployment, it work when I use absolute path. – jcubic Dec 01 '13 at 15:46
  • @chrylis how can I open a file (I need to read it as binary) using getResource? Also I may want to open a file that don't existed when I run the app. – jcubic Dec 01 '13 at 15:48
  • You cannot create the file inside your web application once its deployed. You can read the file inside the war http://stackoverflow.com/questions/3888226/how-can-i-read-file-from-classes-directory-in-my-war – Makky Dec 01 '13 at 15:54

3 Answers3

4

You can read it.

InputStream input = getServletContext().getResourceAsStream("/abc.txt");

or

File file = new File(getServletContext().getRealPath("/abc.txt"));
PearsonArtPhoto
  • 38,970
  • 17
  • 111
  • 142
  • Marking yours as the solution because you provided the code. And it seems that I don't need to call `getServletConfig` method. – jcubic Dec 01 '13 at 16:02
2

Unless your ear is exploded, you cannot get its content via File API. As mentioned above, you should have use getResource. If you wish to work with files in your exploded web archive, you need to get current directory. Use ServletContext.getRealPath(), for example:

String path = getServletContext().getRealPath("/")+"/";
File config = new File(path + "WEB-INF/conf/tag_checker.xml");
File lists = new File(path + "WEB-INF/conf/lists.xml");
Leos Literak
  • 8,805
  • 19
  • 81
  • 156
  • This is a comment not an answer. If you post this as answer then provide some example. – Makky Dec 01 '13 at 15:55
  • Ok, this work `this.getServletConfig().getServletContext().getRealPath(".")` found this looking at javadoc. – jcubic Dec 01 '13 at 15:58
-1

File file=new File("path of file");

Process exec = Runtime.getRuntime().exec("rundll32"+" "+"url.dll,FileProtocolHandler"+" "+file.getAbsolutePath());