使用 Java 部署文本文件,它们应该位于何处?



我有一个Java应用程序,它从一个名为Country.txt的文本文件中读取一些数据。在 Netbeans 中,该文件位于项目级文件夹下。现在我已经在 Netbeans 中对其进行了测试,我可以在不同的计算机上将其作为 jar 文件进行部署和测试。dist 文件夹不包括文本文件,我已手动将其复制到 dist(作为 jar 文件的文件夹(和 dist\lib 文件夹,但我收到"找不到文件"错误。 我的文件没有路径信息,只是...

br = new BufferedReader(new FileReader("Countries.txt"));

有了jar文件,支持文件应该去哪里?

"new File(..("和类似的构造(如"new FileReader(..("(总是构造相对于当前工作目录的路径(除非将绝对路径作为参数传递(。在 IDE 中,这主要是项目的根文件夹(至少在 eclipse 中,从您的描述中,我假设也在 Netbeans 中(。

但是,当您在 IDE 之外运行它时,当前工作目录是您启动 java.exe 的目录。

为了避免这些不一致,我建议将有问题的文件放入声明为类路径中的文件夹(-cp 命令行参数或在 jar 内的 manifest.mf 中定义(。然后,您可以将文件作为资源加载:

this.getClass().getResourceAsStream( "myFile.txt");

编辑:

对于只读资源,建议使用上述方法。这些资源甚至可以放在 jar 文件内的根文件夹中。

但是,如果您必须编辑文件(并将其保存回某个地方(,事情会变得更加复杂。

独立的 Java 应用程序通常具有如下文件夹布局:

myProject
bin
start.bat
lib
myApp.jar
cfg
myApp.properties

通过双击开始.bat你会发现当前目录是myProject/bin。知道了这一点,很容易导航到例如 cfg 目录:

new File(../cfg/myApp.properties)

这对运行时安装有效。但是在 IDE 中,您可能还有另一种布局:

myProject
prod
bin
start.bat
cfg
myApp.properties
src
...
test
...
lib
myApp.jar

如果要在 IDE 中运行时保持相同的硬编码相对路径,则必须在 IDE 的 lauch 配置中配置工作目录。按照上面的例子(日食的例子(:

Working directory = "${workspace_loc:MyProject/prod/bin}". 

在 eclipse 中,这可以在第二个选项卡"参数"上的运行/运行配置中完成。我相信 Netbeans 也有这样的可能性。

在对 SO 和其他地方进行了一些挖掘后,我找到了一种返回绝对路径的方法,并将其添加到我的一般实用程序类中。它似乎适用于我使用过的所有机器 窗口和 linux。

/**
* Returns a String representing the path name of the jar and therefore the
* base locations of the application for supporting files.
*
* @return String representing the base location of the application.
*/
public static String getPathName() {
String fullPath = "";
int endOfPath = 0;
try {
fullPath = new File(JOTI_App.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()).toString();
endOfPath = fullPath.lastIndexOf(File.separatorChar);
} catch (URISyntaxException ex) {
Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
}
return fullPath.substring(0, endOfPath);
}

最新更新