JavaWeb项目读取和修改配置文件问题

来源:互联网 发布:单词社交网络 网盘 编辑:程序博客网 时间:2024/04/30 18:17

JavaWeb项目区别于普通Java项目,它会在服务器中编译,编译后的文件会存在服务器下的Webapps文件夹中,因此,在项目发布后,修改.properties文件,路径成了问题。

InputStream input =PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName);

像上面的加载方式,修改.properties文件后,会将config.properties文件加载到内存中,在下次需要读取时直接从内存中获取文件信息,而不是再次读取。因此要转变输入流获取方式。

String path=PropertiesUtil.class.getClassLoader().getResource(file).getPath();InputStream input=new FileInputStream(path);

下面是我封装的工具类,请多指教。

package com.yc.utils;import java.io.BufferedReader;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.util.HashMap;import java.util.Map;import java.util.Properties;/** * 加载  .properties 文件工具类 * @author S3 * */public class PropertiesUtil {public static Map<String, String> readProperties(String file) throws IOException{Map<String, String> map=new HashMap<String,String>();String path=PropertiesUtil.class.getClassLoader().getResource(file).getPath();InputStream input=new FileInputStream(path);BufferedReader bf=new BufferedReader(new InputStreamReader(input));Properties p = new Properties();try {p.load(bf);} catch (IOException e) {e.printStackTrace();}finally{input.close();bf.close();}if(p.getProperty("name")!=null && p.getProperty("tel")!=null){map.put("name", p.getProperty("name"));map.put("tel", p.getProperty("tel"));return map;}return null;}        //修改方法public static void writeProperties(String file,String name,String tel) throws IOException{FileOutputStream fos = null;try {fos=new FileOutputStream(PropertiesUtil.class.getClassLoader().getResource(file).getPath());Properties p =new Properties();p.setProperty("name", name);p.setProperty("tel", tel);p.store(fos,"保存");} catch (FileNotFoundException e) {e.printStackTrace();}finally{fos.close();}}         //测试类public static void main(String[] args) throws IOException {System.out.println(readProperties("admin.properties"));writeProperties("admin.properties", "a", "110");}}


0 0