【问题标题】:Unable to load external files in java while running in terminal在终端中运行时无法在java中加载外部文件
【发布时间】:2013-12-23 12:28:21
【问题描述】:

我创建了一个可执行的 jar 包(称为 myjar.jar),它有一个用于读取配置文件的类(称为 config_reader)。myjar.jar 之外还有另一个使用 config_reader 的类文件。但是 config_reader 的配置文件放在 myjar.jar 之外(在本地文件系统中)。现在,当我尝试执行可执行 jar 以及另一个使用它的文件时,我收到一条错误消息,提示找不到配置文件:
我试过了 : java -classpath config myclass.class

有人可以帮忙吗?

config_reader的代码是:

public class config_reader()
{
     public static ArrayList<String> get_prop()
    {
        Properties prop = new Properties();
        ArrayList<String> s= new ArrayList<String>();
        try {
               //load a properties file

            prop.load(new FileInputStream("config"));

               //get the property value and print it out
               s.add(prop.getProperty("source_folder_dir"));
               s.add(prop.getProperty("dest_folder_dir"));
               s.add(prop.getProperty("file_type"));
               s.add(prop.getProperty("username"));
               s.add(prop.getProperty("userpwd"));
               s.add(prop.getProperty("exclusion_list"));


        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return s;
    }
}

【问题讨论】:

    标签: java ubuntu terminal classpath config


    【解决方案1】:
    prop.load(new FileInputStream("config"));
    

    不要只说config 使用文件的绝对路径。事实上,这样做更好

        File configFile = new File("absolute path to config file");
        if(configFile.exists()){
            //continue with your logic
        }
    

    【讨论】:

    • 但是这里配置文件的位置不是永久的。有什么方法可以获取当前工作目录,然后参考配置文件的相对位置?
    • 尝试config_reader.class.getProtectionDomain().getCodeSource().getLocation().getPath() 获取当前目录路径。
    猜你喜欢
    • 2021-11-08
    • 1970-01-01
    • 2012-04-11
    • 2022-01-21
    • 2012-06-29
    • 2011-02-25
    • 2021-10-26
    • 2020-11-09
    • 2021-06-30
    相关资源
    最近更新 更多