Java对Properties文件操作小结

187 篇文章 0 订阅

http://javapub.iteye.com/blog/665965


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

Java代码   收藏代码
  1. //读配置文件片段  
  2.   
  3. public String getPropertyValue(String key){  
  4.   Properties pro = new Properties();  
  5.   try {  
  6.    InputStream in = new FileInputStream("");  //加载配置文件  
  7.    try {  
  8.     pro.load(in);  
  9.    } finally {  
  10.     in.close();  
  11.    }  
  12.    return pro.getProperty(key);  
  13.   } catch (Exception e) {  
  14.    e.printStackTrace();  
  15.   
  16.    return null;  
  17.   }  
  18.   
  19. }  


Java代码   收藏代码
  1. //写配置文件片段  
  2.   
  3. public void setPropertyValue(String key, String value){  
  4.   Properties pro = new Properties();  
  5.   try {  
  6.    InputStream in = new FileInputStream("");   //加载配置文件  
  7.    try {  
  8.     pro.load(in);  
  9.    } finally {  
  10.     in.close();  
  11.    }  
  12.      
  13.    pro.setProperty(key, value);  
  14.      
  15.    OutputStream out =new FileOutputStream("");   //加载配置文件  
  16.    try{  
  17.     pro.store(out, "modi by lmy");  
  18.     out.flush();  
  19.    }finally{  
  20.     out.close();  
  21.    }  
  22.      
  23.   } catch (Exception e) {  
  24.    e.printStackTrace();  
  25.   }  
  26. }  

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

这里给大家一个完整的代码,大体方法如此,具体的方法大家手动根据自己的需要去改吧。 
Java代码   收藏代码
  1. import java.io.BufferedReader;  
  2. import java.io.BufferedWriter;  
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.FileOutputStream;  
  6. import java.io.FileReader;  
  7. import java.io.InputStream;  
  8. import java.io.InputStreamReader;  
  9. import java.io.OutputStream;  
  10. import java.io.OutputStreamWriter;  
  11. import java.io.UnsupportedEncodingException;  
  12. import java.util.ArrayList;  
  13. import java.util.Iterator;  
  14. import java.util.List;  
  15. import java.util.Map;  
  16. import java.util.Properties;  
  17.   
  18. import javax.swing.table.TableModel;  
  19.   
  20. import com.peraglobal.core.AnalyserMap;  
  21.   
  22. public class PropertyTool {  
  23.   
  24.     private static Object[][] content;  
  25.   
  26.     public final static void setProperty(Properties pro) {  
  27.   
  28.         List<String> keys = new ArrayList<String>();  
  29.         List<String> values = new ArrayList<String>();  
  30.         content = null;  
  31.   
  32.         Iterator<Map.Entry<Object, Object>> it = pro.entrySet().iterator();  
  33.         String tempValue = "";  
  34.         Object key;  
  35.         Object value;  
  36.         while (it.hasNext()) {  
  37.             Map.Entry<Object, Object> entry = (Map.Entry<Object, Object>) it  
  38.                     .next();  
  39.             // Object key = entry.getKey();  
  40.             key = entry.getKey();  
  41.             value = entry.getValue();  
  42.             keys.add(String.valueOf(key));  
  43.             try {  
  44.                 tempValue = new String(String.valueOf(value).getBytes(  
  45.                         "iso-8859-1"), "utf-8");  
  46.             } catch (UnsupportedEncodingException e) {  
  47.                 e.printStackTrace();  
  48.             }  
  49.             values.add(tempValue);  
  50.         }  
  51.   
  52.         content = new Object[keys.size()][2];  
  53.         for (int i = 0; i < keys.size(); i++) {  
  54.             content[i][0] = keys.get(i);  
  55.             content[i][1] = values.get(i);  
  56.         }  
  57.     }  
  58.   
  59.     public final static List<String> getProperties(String filePath) {  
  60.         try {  
  61.             // 加载配置文件  
  62.             List<String> propCont = new ArrayList<String>();  
  63.             FileInputStream fis = new FileInputStream(filePath);  
  64.             InputStreamReader isr = new InputStreamReader(fis, "utf-8");  
  65.             BufferedReader bufferedreader = new BufferedReader(isr);  
  66.             String temp = "";  
  67.             while ((temp = bufferedreader.readLine()) != null) {  
  68.                 propCont.add(temp);  
  69.             }  
  70.             bufferedreader.close();  
  71.             isr.close();  
  72.             fis.close();  
  73.   
  74.             return propCont;  
  75.   
  76.         } catch (Exception e) {  
  77.             e.printStackTrace();  
  78.             return null;  
  79.         }  
  80.     }  
  81.   
  82.     public final static void saveProperties(String filePath,  
  83.             List<String> content, TableModel tableValues) {  
  84.         try {  
  85.             // 加载配置文件  
  86.             FileReader file = new FileReader(filePath);  
  87.             List<String> propCont = new ArrayList<String>();  
  88.             BufferedReader bufferedreader = new BufferedReader(  
  89.                     new InputStreamReader(new FileInputStream(filePath),  
  90.                             "utf-8"));  
  91.             String temp = "";  
  92.             while ((temp = bufferedreader.readLine()) != null) {  
  93.                 propCont.add(temp);  
  94.             }  
  95.   
  96.             propCont = tableValutToList(propCont, tableValues);  
  97.   
  98.             bufferedreader.close();  
  99.             file.close();  
  100.   
  101.             BufferedWriter br = null;  
  102.             OutputStream outsm = new FileOutputStream(filePath);  
  103.             OutputStreamWriter outFileWriter = new OutputStreamWriter(outsm,  
  104.                     "utf-8");  
  105.             br = new BufferedWriter(outFileWriter);  
  106.   
  107.             br.write(listToString(propCont));  
  108.             br.flush();  
  109.             outFileWriter.flush();  
  110.             outsm.flush();  
  111.   
  112.             br.close();  
  113.             outFileWriter.close();  
  114.             outsm.close();  
  115.   
  116.         } catch (Exception e) {  
  117.             e.printStackTrace();  
  118.         }  
  119.     }  
  120.   
  121.     public static final List<String> tableValutToList(List<String> content,  
  122.             TableModel tableValues) {  
  123.         String keyCell;  
  124.         String valueCell;  
  125.         String rowContent;  
  126.         String[] cellContents;  
  127.         String newContent;  
  128.         // 以原始的文档为依据开始遍历。  
  129.         for (int i = 0; i < content.size(); i++) {  
  130.             rowContent = content.get(i);  
  131.             // 遍历修改后的数据  
  132.             for (int j = 0; j < tableValues.getRowCount(); j++) {  
  133.                 keyCell = String.valueOf(tableValues.getValueAt(j, 1));  
  134.                 valueCell = String.valueOf(tableValues.getValueAt(j, 3));  
  135.                 // 找到原始文件相应的值,并覆盖。  
  136.                 if (0 <= rowContent.indexOf(keyCell)) {  
  137.                     cellContents = rowContent.split("=");  
  138.                     // 判断是否合法,不合法则跳出循环(可能需要更严格的判断,来判断是否是注释等)。  
  139.                     if (0 < cellContents.length  
  140.                             && !cellContents[0].startsWith("#")  
  141.                             && keyCell.trim().toLowerCase().equals(cellContents[0].trim().toLowerCase())) {  
  142.                         newContent = cellContents[0] + "=" + valueCell;  
  143.                         content.set(i, newContent);  
  144.                     }  
  145.                 }  
  146.             }  
  147.         }  
  148.         return content;  
  149.     }  
  150.   
  151.     public static final String listToString(List<String> list) {  
  152.         String str = "";  
  153.         for (int i = 0; i < list.size(); i++) {  
  154.             str = str + list.get(i) + "\n";  
  155.         }  
  156.         return str;  
  157.     }  
  158.   
  159.     /** 
  160.      * 读取配置文件字段。 
  161.      *  
  162.      * @throws Exception 
  163.      * */  
  164.     public final static Object[][] loadProperty(String filePath,  
  165.             AnalyserMap analyserMap) throws Exception {  
  166.         Properties pro = new Properties();  
  167.   
  168.         File curFile = new File(filePath);  
  169.         if (!curFile.exists()) {  
  170.             throw new Exception("文件不存在");  
  171.         }  
  172.         // 加载配置文件  
  173.         InputStream in = new FileInputStream(filePath);  
  174.         try {  
  175.             pro.load(in);  
  176.         } finally {  
  177.             in.close();  
  178.         }  
  179.   
  180.         PropertyTool.setProperty(pro);  
  181.         Object[][] content = PropertyTool.getProperties();  
  182.   
  183.         Object[] temptt;  
  184.         List<Object[]> contentList = new ArrayList<Object[]>();  
  185.         String key;  
  186.         String value;  
  187.         for (int i = 0; i < content.length; i++) {  
  188.             key = String.valueOf(content[i][0]);  
  189.             value = String.valueOf(content[i][1]);  
  190.   
  191.             if (!analyserMap.isVisible(key)) {  
  192.                 continue;  
  193.             }  
  194.   
  195.             temptt = new Object[4];  
  196.             temptt[0] = (i + 1) + "";  
  197.             temptt[1] = key;  
  198.             temptt[2] = analyserMap.getCaption(key);  
  199.             temptt[3] = value;  
  200.   
  201.             contentList.add(temptt);  
  202.         }  
  203.   
  204.         Object[][] reContent = new Object[contentList.size()][];  
  205.         for (int i = 0; i < reContent.length; i++) {  
  206.             temptt = contentList.get(i);  
  207.             reContent[i] = temptt;  
  208.             reContent[i][0] = i + 1 + "";  
  209.   
  210.         }  
  211.   
  212.         return reContent;  
  213.     }  
  214.   
  215.     /** 
  216.      * 读取配置文件字段。 
  217.      *  
  218.      * @throws Exception 
  219.      * */  
  220.     public final static Object[][] loadProperty(String filePath)  
  221.             throws Exception {  
  222.         Properties pro = new Properties();  
  223.   
  224.         File curFile = new File(filePath);  
  225.         if (!curFile.exists()) {  
  226.             throw new Exception("文件不存在");  
  227.         }  
  228.         // 加载配置文件  
  229.         InputStream in = new FileInputStream(filePath);  
  230.         try {  
  231.             pro.load(in);  
  232.         } finally {  
  233.             in.close();  
  234.         }  
  235.   
  236.         PropertyTool.setProperty(pro);  
  237.         Object[][] content = PropertyTool.getProperties();  
  238.   
  239.         Object[] temptt;  
  240.         List<Object[]> contentList = new ArrayList<Object[]>();  
  241.         String key;  
  242.         String value;  
  243.         for (int i = 0; i < content.length; i++) {  
  244.             key = String.valueOf(content[i][0]);  
  245.             value = String.valueOf(content[i][1]);  
  246.   
  247.             temptt = new Object[2];  
  248.             temptt[0] = key;  
  249.             temptt[1] = value;  
  250.   
  251.             contentList.add(temptt);  
  252.         }  
  253.   
  254.         Object[][] reContent = new Object[contentList.size()][];  
  255.         for (int i = 0; i < reContent.length; i++) {  
  256.             temptt = contentList.get(i);  
  257.             reContent[i] = temptt;  
  258.         }  
  259.   
  260.         return reContent;  
  261.     }  
  262.   
  263.     public final static Object[][] getProperties() {  
  264.         return content;  
  265.     }  
  266. }  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值