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

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
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值