java 读取src下的配置文件

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-30 02:22:39

   很多时候,我们都将配置文件放在eclipse的src目录下,这个位置,相当于,当导出可执行jar包后,配置文件放在和jar同级的目录中,比如jar包放在/opt目录下,则配置文件放在/opt下,则jar包就可以读取配置文件中的内容。此时,java代码中可以通过

   String path=CommonOperation.class.getResource("/").getPath();  

   FileInputStream fin = new FileInputStream(path+"Config.properties");

来读取配置文件。

    但要注意,用这种方法在eclipse下调试程序的时候,会发现使用setProperty(String  key ,String value)无法修改配置文件的内容,原因是 eclipse在编译文件时,已经把配置文件复制到工程的bin目录下了,修改其实已经保存在bin目录下的那个配置文件里面了。

java读取配置文件内容的代码如下:

 String path=CommonOperation.class.getResource("/").getPath();
 InputStream fis = new FileInputStream(path+"Config.properties");
 Properties prop = new Properties();
 prop.load(fis);
 fis.close();
 return prop.getProperty(key);

java修改配置文件内容的代码如下:

Properties props = new Properties();
String path=CommonOperation.class.getResource("/").getPath();
FileInputStream fin = new FileInputStream(path+"Config.properties");
props.load(fin); //load file
fin.close();

props.setProperty(key,value);
OutputStream fout = new FileOutputStream(path+"Config.properties");
props.store(fout, "dd");//save file
fout.close();

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!