如何在Struts 2应用程序中阅读文本文件 [英] How can one read a text file in a Struts 2 app

查看:327
本文介绍了如何在Struts 2应用程序中阅读文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

开发Struts 2应用程序我运行在以下问题。我需要读取一个文本文件,部署在我的应用程序的Web服务器。如何知道它的相对路径我可以访问它。换句话说,如果我知道相对路径在部署的目录内,我怎么能找到绝对路径。
当我有类似的问题servlets我曾经使用this.getContextPath()(或类似的东西)返回一个绝对路径到web服务器中的文件夹。

Developing a Struts 2 app I run in a following problem. I need to read a text file that is deployed in web server with my app. How can I access it knowing its relative path. In other words how can I find absolute path if I know relative path inside the deployed directory. When I had similar problem with servlets I used to use this.getContextPath() (or something similar) that returned an absolute path to the folder in the webserver.

编辑:
谢谢你们的答案。对我来说,这样做:

Thank you guys for answer. For me worked this:

String path=GetPointsOfInterestAction.class.getResource("../../../resources/visitor_attractions.txt")

你能解释为什么我的工作,因为我第一步java。

Could you please explain why I it worked because I'm making first steps in java.

推荐答案

如果它放在webapp的类路径中,那么只需使用:

If it is placed in the webapp's classpath, then just use:

InputStream input = servletContext.getResourceAsStream("file.txt");

如果放在全局类路径中,则使用:

If it is placed in the global classpath, then use:

InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("file.txt");

如果将其放在web内容中,则只需使用:

If it is placed in the webcontent, then just use:

InputStream input = new FileInputStream(servletContext.getRealPath("file.txt"));

这些示例假定它们位于根目录中。你当然可以使用相对路径而不是类路径根或web内容根,例如。 path / to / file.txt 。您可以通过 ServletActionContext#getServletContext()获取Struts中的 ServletContext

The examples assumes that they're placed in the root. You can of course use relative path as opposed to the classpath root or webcontent root, e.g. path/to/file.txt. You can get the ServletContext in Struts by ServletActionContext#getServletContext().

修改:您已使用以下内容编辑了问题:

You edited your question with following:


编辑:谢谢你们的回答。对我来说,这样做:

Thank you guys for answer. For me worked this:

String path=GetPointsOfInterestAction.class.getResource("../../../resources/visitor_attractions.txt")

您能解释为什么

这实际上不是正确的方式,但这也是可行的。您只需确保知道文件的相对路径,而不是 GetPointsOfInterestAction 类。这个类当然放在一个不同的包中,所以你基本上需要回一个目录(像你在正常的磁盘文件系统中: cd ../等等)。同样,这不是最优雅的方式。您需要使用前两种方法之一,资源名称 resources / visitor_attractions.txt

This is actually not the "right" way, but this is also doable. You only need to make sure that you know the relative path of the file as opposed to the actual path of the GetPointsOfInterestAction class. This class is of course placed in a different package, so you basically need to step a directory back (like you do in normal disk file systems: cd ../ and so on). Again, this is not the most elegant way. You need to use one of the first two aforementioned ways, with the resource name resources/visitor_attractions.txt.

这篇关于如何在Struts 2应用程序中阅读文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆