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

时间:2015-05-28 20:03:23

标签: java file file-io properties

快一点。我正在尝试部署一个程序,它遵循以下代码。我想读一个名为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)

我正在运行&#34; dist&#34;夹。我已经尝试将属性文件放在带有jar的文件夹中,但没有结果。通常,properties文件位于根项目文件夹中。

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

感谢评论,我根据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