在哪里放置一个.txt文件,以便一个java servlet可以在运行时读取它 [英] Where to place a .txt file so that a java servlet can read it during runtime

查看:94
本文介绍了在哪里放置一个.txt文件,以便一个java servlet可以在运行时读取它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用eclipse来制作一个动态的网页。它是一个简单的程序,依靠servlet传递/检索数据。我的一个servlet必须打开一个.txt文件来读取它的内容并发送给客户端。但是我得到一个FileNotFound异常。我知道它,因为我不知道如何放置txt文件,以便servlet可以在运行时找到该文件。我正在进行日食。你可以提供一些提示吗?

谢谢 解决方案

在类路径(在那里你的Java代码是)或者将它的路径添加到类路径。

  InputStream input = Thread.currentThread ).getContextClassLoader()的getResourceAsStream( file.txt的)。 

或者,把它放在公共webcontent(也就是JSP文件所在的位置)。

  InputStream input = getServletContext()。getResourceAsStream(file.txt); 

至少不要使用 java.io.File 有相对路径,因为这将取决于当前的工作目录,它与启动应用程序的方式有所不同。



另见:




I am using eclipse to make a dynamic webpage. Its a simple program that relies on servlets to pass/retrieve data. One servlet of mine has to open a .txt file to read its content and send it to the client. However I get a FileNotFound Exception. I know its because I don't know how/where to place the txt file so that servlet can find that file at runtime. I am working on eclipse. Can you please provide some hints?

Thanks

解决方案

Put it in the classpath (there where your Java code is) or add its path to the classpath.

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

Or, put it in public webcontent (there where your JSP files also are).

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

You should at least not use java.io.File with relative paths since that would be dependent on the current working directory which differs on the way how you start the application.

See also:

这篇关于在哪里放置一个.txt文件,以便一个java servlet可以在运行时读取它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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