文件与外部文件未发现异常

问题描述 投票:0回答:2

嗨,我已经做了一个小程序,读取配置文件。此文件存储在实际的jar文件之外。在同一水平上的实际jar文件。在运行完美(\测试\ Java的罐子name.jar argument0参数1。即d)当我在实际目录中的命令行启动我的程序。

但是,当我试图从另一个位置运行该程序,然后实际的目录中我得到的filenotfound异常(即d:\ Java的罐子d:\测试\ name.jar argument0参数1)。

基本功能似乎工作,我究竟做错了什么?

按照要求的代码的一部分:

public LoadConfig() {
    Properties properties = new Properties();

    try {
        // load the properties file
        properties.load(new FileInputStream("ibantools.config.properties"));

    } catch (IOException ex) {
        ex.printStackTrace();
    } // end catch

    // get the actual values, if the file can't be read it will use the default values.
    this.environment = properties.getProperty("application.environment","tst");
    this.cbc = properties.getProperty("check.bankcode","true");
    this.bankcodefile = properties.getProperty("check.bankcodefile","bankcodes.txt");
} // end loadconfig

该文件夹是这样的:

这工作:

这不:

罐子不包含文本文件。

java file jar filenotfoundexception
2个回答
2
投票

当使用FileFileInpustream等的字符串/路径构造函数读取文件..相对路径从工作目录导出 - 在你开始你的程序的目录。

当从JAR文件读取,文件是外部罐子,你至少有两个选项:

  1. 提供绝对路径:D:/blah/foo/bar
  2. 让您的文件所在的类路径的目录,并使用this.getClass().getClassLoader().getResourceAsStream("myfile")

后者可能是更适合于阅读存储了与应用程序的位置的路径在配置文件中。


1
投票

有可能是一个更可能:

如果你的代码的一部分被写入文件,另一种是读书,那么这是好事,认为作家写完的文件之前,读者阅读。

您可以穿越把你的代码在调试模式下检查这种情况。如果它工作正常那里,给你FileNotFoundException异常,那么可以肯定这可能是此异常的潜在原因。

现在,如何解决:

您可以使用类似于下面的代码块重试机制的东西

if(!file..exists()){
    Thread.sleep(200);
}

在你的代码,并根据您的需要改变睡眠值。

希望帮助。!

© www.soinside.com 2019 - 2024. All rights reserved.