简体   繁体   English

在使用Netbeans时,在Java Web应用程序中将txt文件添加为资源的位置?

[英]Where to add txt file as resource in Java web app, when using Netbeans?

I want to add a text file as resource in a Java web application. 我想在Java Web应用程序中添加一个文本文件作为资源。 I am using Netbeans as IDE. 我使用Netbeans作为IDE。
I want to keep a file in a folder such that I can directly refer the file rather then a ABSOLUTE path. 我想将文件保存在一个文件夹中,以便我可以直接引用该文件而不是ABSOLUTE路径。

FileInputStream fstream = new FileInputStream("resource.txt");

Where to keep that file in folder? 在文件夹中保存该文件的位置?

Relying on relative file paths is a bad idea as they are dependent on the current working directory (the currently opened directory when the Java application is been started) and you have no control over the current working directory from inside the Java application. 依赖于相对文件路径是一个坏主意,因为它们依赖于当前工作目录(当Java应用程序启动时当前打开的目录)并且您无法从Java应用程序内部控制当前工作目录。

You should rather just put it in the classpath and get it from the classpath: 您应该将它放在类路径中并从类路径中获取它:

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

The above example assumes that the file is placed in classpath root. 上面的示例假定该文件位于类路径根目录中。 If it's in for example the package com.example.resources , then you should get it as follows: 如果它在例如com.example.resources包中,那么你应该得到如下:

InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("com/example/resources/resource.txt");
// ...

If the file is supposed to be editable, then you should really use an absolute disk file system path instead and document it properly in the installation guide of your web application. 如果该文件应该是可编辑的,那么您应该使用绝对磁盘文件系统路径,并在Web应用程序的安装指南中正确记录它。 An alternative is to use a database. 另一种方法是使用数据库。

See also: 也可以看看:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM