如何在servlet中获取本地文件
我在本地设置Tomcat服务器,然后将文本文件放在我的C盘(c:\ test \ myfile.txt)中。
在我的servlet中,我指定了文件的确切路径来读取它。 我成功地做到了。
我的问题是,我应该在部署之前将txt文件放在哪里,如何导航到它来阅读? 我做了一个测试并在我当地的Tomcat上运行
System.out.println("Working Directory = " + System.getProperty("user.dir"));
它向我展示了Eclipse文件夹! 也许是因为我通过eclipse运行tomcat。 所以我确信有一个特定的数据文件夹,或者我应该在文件系统中创建一个但我需要相对路径。
任何建议表示赞赏
这是你的选择。 基本上有三种方式:
将它放在类路径中,以便您可以通过ClassLoader#getResourceAsStream()
以类路径相对路径加载它:
Properties properties = new Properties(); properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("filename.properties"));
这里filename.properties
应该放在webapp的默认类路径所涵盖的一个根中,例如Webapp/WEB-INF/lib
, Webapp/WEB-INF/classes
, Appserver/lib
或JRE/lib
。 如果propertiesfile是特定于webapp的,最好将它放在WEB-INF/classes
。 如果您正在IDE中开发项目,也可以将其放在src文件夹(项目的源文件夹)中。
您也可以将它放在默认类路径之外的某个位置,并将其路径添加到appserver的类路径中。 例如,在Tomcat中,您可以将其配置为Tomcat/conf/catalina.properties
shared.loader属性。
2.)将它放在web文件夹(项目的web内容文件夹)中的某个位置,以便您可以通过ServletContext#getResourceAsStream()
使用webcontent-relative路径加载它:
Properties properties = new Properties(); properties.load(getServletContext().getResourceAsStream("/WEB-INF/filename.properties"));
请注意,我已经演示将文件放在/WEB-INF
文件夹中,否则任何webbrowser都可以公开访问它。 另请注意, ServletContext
位于任何HttpServlet
类中,只能由inheritance的GenericServlet#getServletContext()
。
3.)将它放在本地磁盘文件系统中的某个位置,以便您可以使用绝对本地磁盘文件系统路径以通常的java.io
方式加载它:
Properties properties = new Properties(); properties.load(new FileInputStream("/absolute/path/to/filename.properties");
这里有许多不同的方式,但这取决于您的需求:
要从$TOMCAT_HOME/conf directory
加载属性文件,您需要使用java.io.File
对象访问它,因为类加载器(如在this.getClass().getClassLoader().getResourceAsStream(...)
中只是能够从类路径加载文件(和类)(在WEB-INF/classes
, WEB-INF/lib
或$TOMCAT_HOME/lib
)。
从Tomcat's config directory
加载文件的最简单示例是:
File configDir = new File(System.getProperty("catalina.base"), "conf"); File configFile = new File(configDir, "myconfig.properties"); InputStream stream = new FileInputStream(configFile); Properties props = new Properties(); props.load(stream);
将您的配置文件放在您的webapp WEB-INF / classes文件夹下,并在代码中如下所示
InputStream is= YourClassName.class.getResourceAsStream("myfile.txt");
如果你想在JSP中,你也可以尝试这些其他选项。
String myfile= application.getRealPath("myfile.txt")); or String myfile = getServletContext().getRealPath("myfile.txt"));