繁体   English   中英

程序可以在编译器中正常工作,但不能在jar(Java)中

[英]Program works fine in compiler but not in jar (Java)

我将程序导出到jar文件中,但是当我运行它时,似乎该程序找不到.properties文件。 我确保它在jar文件中,并且在导出之前工作正常。 我读了一些有关使用getClass().getResourceAsStream()而不是FileInputStreamFileOutputStream但似乎无法理解这会如何帮助。 有任何想法吗? 这是使用文件的两种方法。

private void UpdateData() throws IOException{
        FileInputStream in = new FileInputStream("config.properties");
        Properties props = new Properties();
        props.load(in);
        in.close();

        FileOutputStream out = new FileOutputStream("config.properties");
        props.setProperty("prop1", prop1TextArea.getText().toString());
        props.setProperty("prop2", prop2TextArea.getText().toString());
        props.setProperty("prop3", prop3TextArea.getText().toString());
        props.store(out, null);
        out.close();

}

    private void setText() throws IOException {

        FileInputStream in = new FileInputStream("config.properties");
        Properties props = new Properties();
        props.load(in);
        in.close();

        FileOutputStream out = new FileOutputStream("config.properties");
        prop1TextArea.setText(props.getProperty("prop1"));
        prop2TextArea.setText(props.getProperty("prop2"));
        prop3TextArea.setText(props.getProperty("prop3"));
        out.close();
    }

要访问.jar文件中的资源,您必须将它们作为资源而不是文件来访问。

.properties不再在文件系统中,因此您无法通过FileInputStream访问它们。

如果要在以后保存它们,则必须在程序的第一次启动时创建新的.properties 因此,您必须首先检查文件是否存在(例如,通过File.exists() ),然后在没有文件属性的情况下工作,或者创建一个新文件,然后使用它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM