开发者

Where to place the text files required by Jars on a tomcat server?

I have a servlet and inside the WEB-INF/lib directory I have a jar file. This jar is made from a project I am working on. The code in the project executes fine and uses txt files in its main directory. Java code calling these files don't need to add any path, IE:开发者_Go百科 new FileReader("file.txt").

The problem is when I call the servlet it keeps throwing exceptions it can't find those txt files required by the jar. I have placed the txt files in the following locations so far with no luck:

  • Main Directory
  • Source Folder
  • Servlet Package
  • WebContent
  • WEB-INF
  • WEB-INF/lib
  • META-INF

I think I've exhausted all the possible places the txt files could go. Where on earth is the jar file looking for them?

Thank you


Take a look at this post.

It works when you're executing it as a project because that relative path is actually valid on the filesystem. However, once you've packaged your application as a JAR, the usual methods of reading a file will fail because your files are inside the JAR which to the filesystem is just another file. To read resources packaged inside your JAR, you ought to use the Class#getResource() or Class#getResourceAsStream() as appropriate.

You can also checkout what the Java Glosarry on mindprod.com has to say about these:

  • http://mindprod.com/jgloss/resource.html
  • http://mindprod.com/jgloss/getresourceasstream.html


I think I've exhausted all the possible places the txt files could go. Where on earth is the jar file looking for them?

No you didn't. Place the file in the /bin directory inside Tomcat distribution. This construct:

new FileReader("file.txt")

searches for a file in process current directory. After starting Tomcat it happens to be the binary directory that holds all the startup scripts (very unfortunate place).

That said, you should consider rewriting this file reading open and make the path configurable as in most environments reading (and certainly writing to) a /bin directory should be forbidden and is a very bad practice.


I think the answer depends on how Tomcat is started, but often the default directory is the Tomcat root.

Try the following in your servlet:

ServletContext context = getServletConfig().getServletContext ();
String fullPath = context.getRealPath ("file.txt");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜