簡體   English   中英

如何從根目錄加載屬性文件?

[英]How to load a properties file from the root directory?

我目前正在加載這樣的屬性文件:

private Properties loadProperties(String filename) throws IOException{
        InputStream in = ClassLoader.getSystemResourceAsStream(filename);
        if (in == null) {
            throw new FileNotFoundException(filename + " file not found");
        }
        Properties props = new Properties();
        props.load(in);
        in.close();
        return props;
    }

但是,目前我的文件位於 scr\\user.properties 路徑。

但是當我想寫入屬性文件時:

properties.setProperty(username, decryptMD5(password));
        try {
            properties.store(new FileOutputStream("user.properties"), null);
            System.out.println("Wrote to propteries file!" + username + " " + password);

這段代碼在我的項目的根文件夾級別為我生成了一個新文件。

但我想要一個文件來寫\\讀。

因此如何做到這一點?

PS.:當我想指定路徑時,我得到“不允許修改文件......”

創建新文件的原因是您在編寫時嘗試創建新文件。 您應該首先獲取要作為 File 對象寫入的 user.properties 的句柄,然后嘗試寫入它。

代碼看起來像

properties.setProperty(username, decryptMD5(password));
try{
    //get the filename from url class
    URL url = ClassLoader.getSystemResource("user.properties");
    String fileName = url.getFile();

    //write to the file
    props.store(new FileWriter(fileName),null);
    properties.store();
}catch(Exception e){
    e.printStacktrace();
}

暫無
暫無

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

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