`

Java对Properties文件操作小结

阅读更多
经常用到,Java对Properties文件操作,在这里做一个小结。
Java对Properties文件的操作可以说是“不尽人意”,这里时间关系大体先说一下,回头慢慢说。
1.java读Properties文件,经常能读出一些乱码。
2.java写Properties文件,用能把以前的Properties文件的注释弄丢了。

//读配置文件片段

public String getPropertyValue(String key){
  Properties pro = new Properties();
  try {
   InputStream in = new FileInputStream("");  //加载配置文件
   try {
    pro.load(in);
   } finally {
    in.close();
   }
   return pro.getProperty(key);
  } catch (Exception e) {
   e.printStackTrace();

   return null;
  }

}


//写配置文件片段

public void setPropertyValue(String key, String value){
  Properties pro = new Properties();
  try {
   InputStream in = new FileInputStream("");   //加载配置文件
   try {
    pro.load(in);
   } finally {
    in.close();
   }
   
   pro.setProperty(key, value);
   
   OutputStream out =new FileOutputStream("");   //加载配置文件
   try{
    pro.store(out, "modi by lmy");
    out.flush();
   }finally{
    out.close();
   }
   
  } catch (Exception e) {
   e.printStackTrace();
  }
}

上面的public String getPropertyValue(String key)是不存在什么问题的,因为毕竟就是一个读取操作,但是public void setPropertyValue(String key, String value)会出现很严重的问题,因为它会把你文件中所有的注释都忽略掉,你保存文件后发现所有的注释都没有了,解决这个问题我找了好多资料,没有什么好办法。最好利用了一个笨办法,就是写入操作不用Properties类机型操作,而是直接利用文件写入,逐行读入文件,然后后利用key来替换key对应的value。

这里给大家一个完整的代码,大体方法如此,具体的方法大家手动根据自己的需要去改吧。
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.swing.table.TableModel;

import com.peraglobal.core.AnalyserMap;

public class PropertyTool {

	private static Object[][] content;

	public final static void setProperty(Properties pro) {

		List<String> keys = new ArrayList<String>();
		List<String> values = new ArrayList<String>();
		content = null;

		Iterator<Map.Entry<Object, Object>> it = pro.entrySet().iterator();
		String tempValue = "";
		Object key;
		Object value;
		while (it.hasNext()) {
			Map.Entry<Object, Object> entry = (Map.Entry<Object, Object>) it
					.next();
			// Object key = entry.getKey();
			key = entry.getKey();
			value = entry.getValue();
			keys.add(String.valueOf(key));
			try {
				tempValue = new String(String.valueOf(value).getBytes(
						"iso-8859-1"), "utf-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			values.add(tempValue);
		}

		content = new Object[keys.size()][2];
		for (int i = 0; i < keys.size(); i++) {
			content[i][0] = keys.get(i);
			content[i][1] = values.get(i);
		}
	}

	public final static List<String> getProperties(String filePath) {
		try {
			// 加载配置文件
			List<String> propCont = new ArrayList<String>();
			FileInputStream fis = new FileInputStream(filePath);
			InputStreamReader isr = new InputStreamReader(fis, "utf-8");
			BufferedReader bufferedreader = new BufferedReader(isr);
			String temp = "";
			while ((temp = bufferedreader.readLine()) != null) {
				propCont.add(temp);
			}
			bufferedreader.close();
			isr.close();
			fis.close();

			return propCont;

		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public final static void saveProperties(String filePath,
			List<String> content, TableModel tableValues) {
		try {
			// 加载配置文件
			FileReader file = new FileReader(filePath);
			List<String> propCont = new ArrayList<String>();
			BufferedReader bufferedreader = new BufferedReader(
					new InputStreamReader(new FileInputStream(filePath),
							"utf-8"));
			String temp = "";
			while ((temp = bufferedreader.readLine()) != null) {
				propCont.add(temp);
			}

			propCont = tableValutToList(propCont, tableValues);

			bufferedreader.close();
			file.close();

			BufferedWriter br = null;
			OutputStream outsm = new FileOutputStream(filePath);
			OutputStreamWriter outFileWriter = new OutputStreamWriter(outsm,
					"utf-8");
			br = new BufferedWriter(outFileWriter);

			br.write(listToString(propCont));
			br.flush();
			outFileWriter.flush();
			outsm.flush();

			br.close();
			outFileWriter.close();
			outsm.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static final List<String> tableValutToList(List<String> content,
			TableModel tableValues) {
		String keyCell;
		String valueCell;
		String rowContent;
		String[] cellContents;
		String newContent;
		// 以原始的文档为依据开始遍历。
		for (int i = 0; i < content.size(); i++) {
			rowContent = content.get(i);
			// 遍历修改后的数据
			for (int j = 0; j < tableValues.getRowCount(); j++) {
				keyCell = String.valueOf(tableValues.getValueAt(j, 1));
				valueCell = String.valueOf(tableValues.getValueAt(j, 3));
				// 找到原始文件相应的值,并覆盖。
				if (0 <= rowContent.indexOf(keyCell)) {
					cellContents = rowContent.split("=");
					// 判断是否合法,不合法则跳出循环(可能需要更严格的判断,来判断是否是注释等)。
					if (0 < cellContents.length
							&& !cellContents[0].startsWith("#")
							&& keyCell.trim().toLowerCase().equals(cellContents[0].trim().toLowerCase())) {
						newContent = cellContents[0] + "=" + valueCell;
						content.set(i, newContent);
					}
				}
			}
		}
		return content;
	}

	public static final String listToString(List<String> list) {
		String str = "";
		for (int i = 0; i < list.size(); i++) {
			str = str + list.get(i) + "\n";
		}
		return str;
	}

	/**
	 * 读取配置文件字段。
	 * 
	 * @throws Exception
	 * */
	public final static Object[][] loadProperty(String filePath,
			AnalyserMap analyserMap) throws Exception {
		Properties pro = new Properties();

		File curFile = new File(filePath);
		if (!curFile.exists()) {
			throw new Exception("文件不存在");
		}
		// 加载配置文件
		InputStream in = new FileInputStream(filePath);
		try {
			pro.load(in);
		} finally {
			in.close();
		}

		PropertyTool.setProperty(pro);
		Object[][] content = PropertyTool.getProperties();

		Object[] temptt;
		List<Object[]> contentList = new ArrayList<Object[]>();
		String key;
		String value;
		for (int i = 0; i < content.length; i++) {
			key = String.valueOf(content[i][0]);
			value = String.valueOf(content[i][1]);

			if (!analyserMap.isVisible(key)) {
				continue;
			}

			temptt = new Object[4];
			temptt[0] = (i + 1) + "";
			temptt[1] = key;
			temptt[2] = analyserMap.getCaption(key);
			temptt[3] = value;

			contentList.add(temptt);
		}

		Object[][] reContent = new Object[contentList.size()][];
		for (int i = 0; i < reContent.length; i++) {
			temptt = contentList.get(i);
			reContent[i] = temptt;
			reContent[i][0] = i + 1 + "";

		}

		return reContent;
	}

	/**
	 * 读取配置文件字段。
	 * 
	 * @throws Exception
	 * */
	public final static Object[][] loadProperty(String filePath)
			throws Exception {
		Properties pro = new Properties();

		File curFile = new File(filePath);
		if (!curFile.exists()) {
			throw new Exception("文件不存在");
		}
		// 加载配置文件
		InputStream in = new FileInputStream(filePath);
		try {
			pro.load(in);
		} finally {
			in.close();
		}

		PropertyTool.setProperty(pro);
		Object[][] content = PropertyTool.getProperties();

		Object[] temptt;
		List<Object[]> contentList = new ArrayList<Object[]>();
		String key;
		String value;
		for (int i = 0; i < content.length; i++) {
			key = String.valueOf(content[i][0]);
			value = String.valueOf(content[i][1]);

			temptt = new Object[2];
			temptt[0] = key;
			temptt[1] = value;

			contentList.add(temptt);
		}

		Object[][] reContent = new Object[contentList.size()][];
		for (int i = 0; i < reContent.length; i++) {
			temptt = contentList.get(i);
			reContent[i] = temptt;
		}

		return reContent;
	}

	public final static Object[][] getProperties() {
		return content;
	}
}


分享到:
评论

相关推荐

    Java高级程序设计实战教程第三章-Java反射机制.pptx

    Java高级程序设计 第3章 Java反射机制 3.1 应用场景 3.2 相关知识3.3 实施过程 3.4 拓展知识3.5 拓展训练 3.6 课后小结3.7 课后习题 3.8 上机实训 Java高级程序设计实战教程第三章-Java反射机制全文共15页,当前为第...

    java基础案例与开发详解案例源码全

    13.1.2 Java对文件和目录的操作328 13.2 JavaIO原理332 13.3 流类结构333 13.3.1 InputStream和OutputStream333 13.3.2 Reader和Writer334 13.4 文件流336 13.4.1 FileInputStream和FileOutputStream336 13.4.2 ...

    java范例开发大全源代码

     实例127 一个文件变成多个小文件 178  实例128 多个小文件合成一个文件 181  实例129 统计指定文件中的字符个数 183  实例130 对象的序列化与反序列化 185  实例131 同时显示多个文件 187  实例132...

    java范例开发大全

    实例221 改变Properties文件中的键值 399 第13章 多线程编程(教学视频:121分钟) 405 13.1 多线程的五种基本状态 405 实例222 启动线程 405 实例223 参赛者的比赛生活(线程休眠唤醒) 407 实例224 资源搜索并下载...

    Java范例开发大全 (源程序)

     实例221 改变Properties文件中的键值 399  第13章 多线程编程(教学视频:121分钟) 405  13.1 多线程的五种基本状态 405  实例222 启动线程 405  实例223 参赛者的比赛生活(线程休眠唤醒) 407  实例...

    java范例开发大全(pdf&源码)

    实例221 改变Properties文件中的键值 399 第13章 多线程编程(教学视频:121分钟) 405 13.1 多线程的五种基本状态 405 实例222 启动线程 405 实例223 参赛者的比赛生活(线程休眠唤醒) 407 实例224 资源搜索并下载...

    Java范例开发大全(全书源程序)

    实例221 改变Properties文件中的键值 399 第13章 多线程编程(教学视频:121分钟) 405 13.1 多线程的五种基本状态 405 实例222 启动线程 405 实例223 参赛者的比赛生活(线程休眠唤醒) 407 实例224 资源搜索...

    面向对象技术与UML课件及源代码-by 南邮-陈杨

    1.5小结 第2章程序设计基础:变量及其运算 2.1认识变量 2.1.1变量的定义 2.1.2变量有哪些类型 2.2如何使用变量 2.2.1如何使用整型变量 2.2.2如何使用浮点型变量 2.2.3如何使用字符型变量 2.2.4如何使用布尔...

    深入浅出Struts2(附源码)

    2.4.2 struts.properties文件 26 2.5 Struts应用程序示例 26 2.5.1 部署描述文件和Struts配置文件 27 2.5.2 动作类 28 2.5.3 运行app02a程序 29 2.6 依赖注入 29 2.6.1 概述 29 2.6.2 依赖注入的几种方式 31 ...

    深入浅出Struts 2 .pdf(原书扫描版) part 1

    2.4.2 struts.properties文件 26 2.5 Struts应用程序示例 26 2.5.1 部署描述文件和Struts配置文件 27 2.5.2 动作类 28 2.5.3 运行app02a程序 29 2.6 依赖注入 29 2.6.1 概述 29 2.6.2 依赖注入的几种方式 31 2.7 小...

    mybatis学习笔记

    5.5 resultMap小结 55 5.6 延迟加载 56 5.6.1 打开延迟加载开关 56 5.6.2 一对一查询延迟加载 56 5.6.3 一对多延迟加载 59 5.6.4 延迟加载小结 59 6 查询缓存 59 6.1 mybatis缓存介绍 59 6.2 一级缓存 60 6.2.1 原理...

    Eclipse权威开发指南2.pdf

    1.5 本章小结...... 11 1.6 参考文献...... 12 第2章 Eclipse入门 13 2.1 第一步...... 14 2.1.1 提示没有任何JRE可用的对话框..... 14 2.1.2 创建您的第一个项目..... 15 2.1.3 Eclipse的外观:编辑器、视图和...

    Eclipse_Swt_Jface_核心应用_部分19

    1.7 本章小结 10 第2章 配置SWT开发环境 11 2.1 下载和安装Eclipse 11 2.1.1 Eclipse下载页面介绍 11 2.1.2 下载Eclipse 12 2.1.3 安装Eclipse语言包 14 .2.1.4 在不同的语言中切换 15 2.2 直接获取...

    iBATIS实战

    1.5 小结 24 第2章 iBATIS是什么 26 2.1 映射SQL语句 27 2.2 iBATIS如何工作 29 2.2.1 iBATIS之于小型、简单系统 30 2.2.2 iBATIS之于大型、企业级系统 31 2.3 为何使用iBATIS 31 2.3.1 简单性 32 2.3.2 生产效率 ...

    Eclipse权威开发指南3.pdf

    1.5 本章小结...... 11 1.6 参考文献...... 12 第2章 Eclipse入门 13 2.1 第一步...... 14 2.1.1 提示没有任何JRE可用的对话框..... 14 2.1.2 创建您的第一个项目..... 15 2.1.3 Eclipse的外观:编辑...

    Eclipse权威开发指南1.pdf

    1.5 本章小结...... 11 1.6 参考文献...... 12 第2章 Eclipse入门 13 2.1 第一步...... 14 2.1.1 提示没有任何JRE可用的对话框..... 14 2.1.2 创建您的第一个项目..... 15 2.1.3 Eclipse的外观:编辑...

    JAVA_MuntiSocket_Chat:实习

    此项目是学校安排的大四企业实习课程的小结。综合利用了学过的JAVA的API和特性,写出一个C/S架构的简易聊天程序,功能简陋,还有许多待完善之处。 实现顺序 使用Properties类生成配置文件。 编写Socket和...

Global site tag (gtag.js) - Google Analytics