Eclipse:获取差异“当前目录的路径”当作为“Java应用程序”运行时和“在服务器上”
我使用tomcat服务器,并尝试从servlet调用java类,该类具有返回系统当前目录路径的方法。它的结果与我在该类中运行 form main 方法时的结果不同。
- 来自 main 方法:“D:\Projects\Eclipse\Assignment”(这是我放置项目的位置)
- 是我放置 eclipse 的位置)
来自 servlet:“D:\IDE\eclipse helios”(这 访问我的项目文件夹中的 xml 文件(当我从 servlet 调用类时,找不到文件异常)。我希望从 servlet 调用时得到与运行 main 方法时相同的结果。我怎样才能做到这一点?
我将不胜感激您能给我的任何建议,或者您可以推荐的任何文章。
谢谢。
I use tomcat server, and try to call a java class from servlet, that class has method which will return system current directory path. It's result is difference with the one when I run form main method in that class.
- from main method: "D:\Projects\Eclipse\Assignment" (which is where i place my project)
- from servlet: "D:\IDE\eclipse helios" ( which is where i place my eclipse)
With this I have trouble to access my xml file in my project folder( file not found exception when I call a class from servlet). I want the same result when call from servlet as when run main method. How can I do that?
I would appreciate any advice you could give me to, or any articles that you could recommend.
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为什么要尝试从文件系统访问资源?从任何 JAR(包括 Web 应用程序)访问资源的预期方法是使用 getResourceAsStream:
http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#getResourceAsStream(java.lang.String)
即,将包含资源的文件夹添加到构建路径,并使用
YourClassName.class.getResourceAsStream("/foo.xml")
访问它。Why are you trying to access your resources from the filesystem? The expected method of accessing resources from any JAR, including webapps, is using getResourceAsStream:
http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#getResourceAsStream(java.lang.String)
i.e. add the folder containing your resource to the build path, and use
YourClassName.class.getResourceAsStream("/foo.xml")
to access it.问:你明白为什么“当前目录”位于两个不同的地方,对吗?一个地方是您运行 Java 程序的地方(当您“运行方式,Java 程序”时),另一个地方是您运行 Web 服务器的地方(当您“运行方式,Web 应用程序”时)。
问:对于您目前的情况,为什么不直接使用绝对路径(例如“d:\projects\data”)?
Q: You understand why "current directory" is in two different places, correct? One place is where you're running your Java program (when you "Run As, Java Program"), and the other place is where you're running your web server (when you "Run As, Web App").
Q: For your current situation, why not just use an absolute path (e.g. "d:\projects\data")?