快速之一。我试图部署一个程序,它在以下代码中生效。我想读取一个名为,properties
的属性文件。的Java - 运行JAR拒绝加载文件在同一目录
Properties props = new Properties();
InputStream is;
// First try - loading from the current directory
try {
File f = new File("properties");
is = new FileInputStream(f);
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace(System.err);
is = null;
}
try {
if (is == null) {
// Try loading from classpath
is = getClass().getResourceAsStream("properties");
}
//Load properties from the file (if found), else crash and burn.
props.load(is);
} catch (IOException e) {
e.printStackTrace(System.err);
}
当我通过Netbeans运行程序时,一切顺利。
当我单独运行JAR时,虽然有,但我得到两个例外。
java.io.FileNotFoundException: properties (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
.
.
.
Exception in Application start method
Exception in Application stop method
java.lang.reflect.InvocationTargetException
.
.
.
(exception during props.load(is) because is == null)
我从“dist”文件夹运行文件。我已经尝试将属性文件放在jar文件夹内,没有结果。通常,properties
文件位于根项目文件夹中。
任何想法?
尝试使用绝对路径到文件。当您从类路径请求文件时,请确保该文件确实位于类路径中,可以使用java VM选项的“-cp/some/dir”。还请尝试使用前导斜杠字符,以便请求的资源具有绝对路径,如“/ properties”。如果您仍然有问题,可以确认您正在使用的平台以及Java VM启动选项和命令行。 –
它应该在您运行'java'命令的目录中。否则,它正在看Jar本身,这是你的第二个'尝试'。你期望它能在文件系统或jar中找到它吗? – RealSkeptic
如果你想读相对于当前目录中的文件,该文件必须是在你的,不一定是罐子在目录中运行该命令的目录 –