2014-10-30 116 views
0

我想在属性文件中保留一些属性,以防程序运行期间发生更改。现在我试图这样做:Java:在类路径上加载和编辑属性文件

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); 
    } 

但它似乎并没有工作。我究竟做错了什么?

+0

嗯,我试图做同样的事情,并注意到我的属性并未实际加载。我无法获得我在文件中定义的道具。 – pbespechnyi 2014-10-30 20:02:39

回答

1

如果文件与程序位于同一目录中,则不需要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

3

为了能够读写属性文件,它是在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() 

获取绝对路径给你的文件。

P.S.只是为了确保你正在检查正确的文件。您不应该检查resources文件夹中的文件。修改后的文件将与您的课程放在根文件夹中,如targetout

0

如果你要坚持性文件处理通过类路径 - 你当然可以使用下面的代码,因为它是,我认为这是处理类路径文件中两个最简单的方法 - 阅读和写作目的

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()); 
    }