簡體   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