Java - 运行 JAR 拒绝加载同一目录中的文件

Java - Running JAR refuses to load file in the same directory

快点。我正在尝试部署一个程序,该程序在以下代码处出现问题。我想阅读一个名为 properties.

的属性文件
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 文件位于根项目文件夹中。

有什么想法吗?

您将文件作为资源阅读 (getResourceAsStream("properties");)。所以它必须在类路径中。也许直接在 jar 中或在您添加到类路径的目录中。

jar 是一个 zip 文件,因此您可以使用 7zip 打开它,例如将您的属性文件添加到 jars 根级别并重试。

感谢评论,我根据jar的当前运行目录构建了一个绝对路径生成器。伙计们,给你们点赞。

private String relativizer(String file) {
    URL url = RobotikosAnomologitos.class.getProtectionDomain().getCodeSource().getLocation();
    String urlString = url.toString();
    int firstSlash = urlString.indexOf("/");
    int targetSlash = urlString.lastIndexOf("/", urlString.length() - 2) + 1;

    return urlString.substring(firstSlash, targetSlash) + file;
}

所以我新的文件读取结构是:

        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
                String pathToProps = relativizer("properties");       
                is = new FileInputStream(new File(pathToProps));
                //is = getClass().getResourceAsStream(pathToProps);
            }
            //Load properties from the file (if found), else crash and burn.
            props.load(is);
        } catch (IOException e) {
            e.printStackTrace(System.err);
        }
        // Finally parse the properties. 
        //code here, bla bla