簡體   English   中英

Java:在類路徑上加載和編輯屬性文件

[英]Java: load and edit properties file on classpath

我想將一些屬性保留到屬性文件中,以防它們在程序運行期間被更改。 現在,我正在嘗試這樣做:

Properties properties = new Properties();

    try (FileInputStream in = new FileInputStream("classpath:app.properties")) {
        properties.load(in);
    } catch (IOException e) {
        logger.error("", e);
    }

    properties.setProperty("word", "abc");

    try (FileOutputStream out = new FileOutputStream("classpath:app.properties")) {
       properties.store(out, null);
    } catch (IOException e) {
        logger.error("", e);
    }

但這似乎不起作用。 我究竟做錯了什么?

為了能夠讀取和寫入resources文件夾(在標准maven項目結構中)中的屬性文件,可以使用以下命令:

// of course, do not forget to close the stream, after your properties file has been read.
properties.load(Runner.class.getClassLoader().getResourceAsStream("app.properties"));

修改屬性文件后,可以使用類似以下內容的東西:

Runner.class.getClassLoader().getResource("app.properties").getFile()

獲取文件的絕對路徑。

PS只是為了確保您正在檢查正確的文件。 您不應該檢查resources文件夾中的文件。 修改后的文件將與您的類一起放置在根文件夾中,例如targetout

如果文件與程序位於同一目錄中,則不需要classpath部分。

Properties properties = new Properties();

try (FileInputStream in = new FileInputStream("app.properties")) {
    properties.load(in);
} catch (IOException e) {
    logger.error("", e);
}

properties.setProperty("word", "abc");

try (FileOutputStream out = new FileOutputStream("app.properties")) {
   properties.store(out, null);
} catch (IOException e) {
    logger.error("", e);
}

否則,如果文件在jar中,則必須重新打包jar

如果您要堅持通過類路徑處理屬性文件-您當然可以按原樣使用以下代碼,我認為這是在類路徑中同時處理文件和文件的最簡單方法-讀寫目的

try{

    InputStream in =   this.getClass().getResourceAsStream("/suggest.properties");
    Properties props = new Properties();
    props.load(in);
    in.close();


    URL url = this.getClass().getResource("/suggest.properties");
    File fileObject = new File(url.toURI());

    FileOutputStream out = new FileOutputStream(fileObject);

    props.setProperty("country", "america");
    props.store(out, null);
    out.close();

    }catch(Exception e)
    {
        System.out.println(e.getMessage());
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM