从 servlet 读取外部文件
每当我使用 new File() 而不使用绝对路径在 servlet 中读取或写入文件时,我得到的路径都位于 eclipse 文件夹内。我不知道发生了什么事。有谁对我面临的问题有任何想法。
whenever I am reading or writing a file in a servlet using new File()
without using absolute path, the path I am getting is inside the eclipse folder. I don't know what is happening. Does anyone have any idea abut the problem I am facing.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
基本上,您不应该只在 servlet 中使用相对文件名:servlet 容器将为您提供某些目录位置的映射,如果您需要其他任何内容,您应该在 servlet 参数中指定。
例如,查看
ServletContext.getRealPath
。如果您能告诉我们更多有关您正在尝试做什么的信息,那将会有所帮助。
Basically you shouldn't just use relative filenames within servlets: the servlet container will provide you with mappings for some directory locations, and if you need anything else you should specify that in your servlet parameters.
For example, look at
ServletContext.getRealPath
.If you can tell us more about what you're trying to do, that would help.
如果是为了读取配置文件,您应该使用 ServletContext.getResourceAsStream(java.lang.String path),该方法将从您引用的资源返回一个 InputStream,我建议您将这些文件保存在您的WEB-INF 文件夹。
如果要写入文件,您应该始终提供(最好在可配置位置)需要写入的目录的绝对路径,并确保它存在并具有执行此类操作的适当权限。
If it's for reading configuration files you should use the
ServletContext.getResourceAsStream(java.lang.String path)
, The method will return an InputStream from the resource you have referenced and I advice you keep such files under your WEB-INF folder.If you want to write files you should always provide (preferably in a configurable location) the absolute path to the directory you need to write in, as well as make sure it exists and has the appropriate permissions for such an operation.
这是因为eclipse默认的工作目录是项目文件夹。如果您想使用相对路径将文件写入指定文件夹中,我建议您这样做:
这意味着您的项目假装在指定目录中运行。
希望我能帮助好运。
It is because the default working directory of eclipse is the project folder. If u want to write the file in a specified folder using a relative path I suggest you do this:
This means that your project pretends to run in the specified directory.
Hope I helped good luck.