java-- properties总结
轉載自? java-- properties總結
?
篇章一:Loading Properties from XML
XML 屬性文檔具有以下 DOCTYPE 聲明: <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd"> 注意,導入或導出屬性時不 訪問系統 URI (http://java.sun.com/dtd/properties.dtd);該系統 URI 僅作為一個惟一標識 DTD 的字符串:
<?xml version="1.0" encoding="UTF-8"?> <!-- DTD for properties --> <!ELEMENT properties ( comment?, entry* ) > <!ATTLIST properties version CDATA #FIXED "1.0"> <!ELEMENT comment (#PCDATA) > //注釋 <!ELEMENT entry (#PCDATA) > //值 <!ATTLIST entry key CDATA #REQUIRED> //key下面給出一個實例:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd"> <properties> <comment>Hi</comment> <entry key="foo">bar</entry> <entry key="fu">baz</entry> </properties>下面運用loadFromXML(InputStream is)讀取xml:
import java.util.*; import java.io.*; public class LoadSampleXML { public static void main(String args[]) throws Exception { Properties prop = new Properties(); FileInputStream fis = new FileInputStream("sampleprops.xml"); prop.loadFromXML(fis); prop.list(System.out);//將屬性列表輸出到指定的輸出流 System.out.println(" The foo property: " + prop.getProperty("foo")); } }?
?下面運用storeToXML(OutputStream os, String comment)方法來創建xml:
?
import java.util.*; import java.io.*; public class StoreXML { public static void main(String args[]) throws Exception { Properties prop = new Properties(); prop.setProperty("one-two", "buckle my shoe"); prop.setProperty("three-four", "shut the door"); prop.setProperty("five-six", "pick up sticks"); prop.setProperty("seven-eight", "lay them straight"); prop.setProperty("nine-ten", "a big, fat hen"); FileOutputStream fos = new FileOutputStream("rhyme.xml"); prop.storeToXML(fos, "Rhyme"); //傳遞一個輸出流及一個注釋的String fos.close(); } }?
輸出打印的結果為:
?
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>Rhyme</comment>
<entry key="seven-eight">lay them straight</entry>
<entry key="five-six">pick up sticks</entry>
<entry key="nine-ten">a big, fat hen</entry>
<entry key="three-four">shut the door</entry>
<entry key="one-two">buckle my shoe</entry>
</properties>
為什么會選擇把properties和xml關聯起來?
J2SE1.5以前的版本要求直接使用XML解析器來裝載配置文件并存儲設置。雖然這并非是一件困難的事情,并且解析器是平臺的標準部分,但是額外的工作總是有點讓人煩。最近更新的java.util.Properties類現在提供了一種為程序裝載和存儲設置的更容易的方法:loadFromXML(InputStream is)和storeToXML(OutputStream os, String comment)方法。使用 XML 文件還是使用老式的 a=b 類型的文件完全取決于您自己。老式文件從內存的角度看肯定是輕量級的。不過,由于 XML 的普遍使用,人們會期望 XML 格式流行起來,因為它已經被廣泛使用了,只不過沒有用到 Properties 對象。
不過在我看來properties同xml一樣,引用API中的一句話:“它將資源包中大部分(如果不是全部)特定于語言環境的信息隔離開來。”,讓我們可以輕松的進行修改及動態載入。
篇章二:更好理解它的方法
在開始這一篇章的講解之前,我們先提一下兩個類:
FileInputStream類:一個文件字節輸入流,從中可以讀出一個字節或一批字節
FileOutputStream類:一個文件字節輸出流,可向流中寫一個字節或一批字節
第一個方法:public void load(InputStream inStream) throws IOException從輸入流中讀取屬性列表(鍵和元素對)。
第二個方法:public void store(OutputStream out,String comments)throws IOException將load方法讀取到的屬性列表寫入out流中。這里的comments是注釋
下面我們用代碼來說明:
這里我們已經創建了兩個properties文件:
文件1:
#test.properties
1=a
2=b
3=c
文件二:
#temp.test.properties
today=Monday
tomorrow=Tuesday
下面我們將就Store方法進行討論
?
演示代碼的結果是test.properties中的內容不變
而temp.properties中的內容如下:
#Update '2' value?
#Sun Dec 02 00:16:31 CST 2007
3=c
2=w
1=a
我們可以發現當我們得到test.properties的屬性列表后并調用setProperty對屬性列表做出修改后得到的新的屬性列表覆蓋了temp.properties的內容。輸入順序正如api文檔所述:如果 comments 變量非 null,則首先將 ASCII # 字符、注釋字符串和一個行分隔符寫入輸出流。因此,該 comments 可用作一個標識注釋。接下來總是寫入一個注釋行,該行包括一個 ASCII # 字符、當前的日期和時間(就好像使用 Date 的 toString 方法獲取當前時間一樣)和一個由 Writer 生成的行分隔符。然后將此 Properties 表中的所有項寫入 out,一次一行。
如果只想在temp.properties的后面添加而不希望覆蓋 ,我們只需這樣寫new FileOutputStream(String name,true)即可。
下面我們將寫一個讀properties的模塊:
?
Enumeration<?> enumeration = prop.propertyNames(); while (enumeration.hasMoreElements()) { String propertyname = enumeration.nextElement().toString(); System.out.println(propertyname + ":" + prop.getProperty(propertyname, "unknown"));當然在運用它時你還要把它補充完整。如果你夠仔細,你將會在前面的代碼中找到怎樣同過key得到value的方法??
篇章3:如何解決中文亂碼的問題
如果你的properties文件中含有中文,在不做任何處理的情況下你得到的將是一連串的問號。在那一步中產生了這一問題呢?在API中我們可以在load方法中閱讀這一段:假定該流使用 ISO 8859-1 字符編碼;也就是每個字節是一個 Latin1 字符。對于非 Latin1 的字符和某些特殊字符,可以使用與字符和字符串字面值所用的類似轉義序列。
也就是說我們要把漢字轉換為/uXXXX。
如何做到這一點,我這里有兩個辦法:
辦法一:使用native2ascii 命令(具體用法csdn上可以搜到很多)。
辦法二:重寫native2ascii命令
對于辦法二,我重寫了一個模塊,基本實現native2ascii的轉義功能:
?
在寫這個模塊之前我使用的是這個模塊當然這個模塊經常被用來處理jsp的中文字符問題
代碼如下:
?
package com.build; import java.util.ArrayList; import java.util.PropertyResourceBundle; import java.io.*; /** *author:Aivin Ray *publish data:2007-12-1 *tips:the segment of my project **/ public class ProperitiesRead { private static PropertyResourceBundle Config = null; private static final String CONFIGKEY_House_PREFIX = "HouseGrade"; ArrayList<String> list = new ArrayList<String>(); public ProperitiesRead(String file) { setconfigfile(getClass().getResourceAsStream(file)); } public boolean setconfigfile(InputStream in) { boolean is = true; if (in != null) { try { Config = new PropertyResourceBundle(in); } catch (IOException e) { // TODO 自動生成 catch 塊 is = false; } if (is) { try { int index = 0; while (true) { String keyvalue1 = getkeyvalue(Config.getString(CONFIGKEY_House_PREFIX + index)) list1.add(keyvalue1); index++; } } catch (Exception ex) { } } } return is; } public ArrayList<String> getHouseGrade() { return list; } /*解決亂碼問題,可以提取出來做為模塊使用*/ public String getkeyvalue(String key) { String keyvalue = null; try { keyvalue = new String(key.getBytes("ISO-8859-1"), "gb2312"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return keyvalue; } }篇章4:讀取Properties文件三種方法?
1。使用java.util.Properties類的load()方法
示例:InputStream in=new BufferedInputStream(new FileInputStream(name));
或者 InputStream in=JProperties.class.getResourceAsStream(name);
或者 InputStream in=JProperties.class.getClassLoader().getResourceAsStream(name);
或者 InputStreamin=ClassLoader.getSystemResourceAsStream(name);
然后:?
Properties p=new Properties();
p.load(in);
2。使用java.util.ResourceBundle類的getBundle()方法
示例:ResourceBundlerb=ResourceBundle.getBundle(name,Locale.getDefault());
3。使用java.util.PropertyResourceBundle類的構造函數
示例:InputStream in=new BufferedInputStream(new FileInputStream(name));
ResourceBundler b=new PropertyResourceBundle(in);
補充:
Servlet中可以使用javax.servlet.ServletContext的getResourceAsStream()方法
示例:InputStreamin=context.getResourceAsStream(path);
Properties p=new Properties();
p.load(in);
篇章五:最后的模塊——對properites值的修改
package com.builder; /** * @author Aivin.Ray * @data 2007-12-1 */ import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; //前一篇已介紹此方法 import com.builder.ToUnicode; public class CreatePro { //讀文件 public static String readFile(String filePath, String parameterName) throws IOException, FileNotFoundException { String result = null; File file = new File(filePath); if (file.exists()) { FileInputStream fis = new FileInputStream(file); byte[] b = new byte[fis.available()]; fis.read(b); result = new String(b, "UTF-8"); fis.close(); } return result; } //修改后存儲 public static void saveFile(String content, String path, String fileName) throws IOException { File f = new File(path); if (!f.exists()) { f.mkdirs(); } File fn = new File(f, fileName); FileOutputStream fos = new FileOutputStream(fn); fos.write(content.getBytes()); fos.close(); } //刪除舊文件 public static void deleteFile(String path) throws IOException { File f = new File(path); if (f.exists()) { f.delete(); } else { throw new IOException("未找到相關文件"); } } //執行方法 public static boolean writeProperties(String filePath, String parameterName, String parameterValue) { boolean flag = false; try { //取得文件所有內容 String all = CreatePro.readFile(filePath, parameterName); String result = null; //如果配置文件里存在parameterName if (all.indexOf(parameterName) != -1) { //得到parameterName前的字節數 int a=all.indexOf(parameterName); //取得以前parameterName的值 String old = readProperties(filePath, parameterName); //得到parameterName值前的字節數 int b=a+(parameterName.length()+"=".length()); //新的properties文件所有內容為:舊的properties文件中內容parameterName+"="+新的parameterName值(parameterValue)+舊的properties文件中parameterName值之后的內容 result=all.substring(0,a)+parameterName+"="+parameterValue+all.substring(b+ToUnicode.convert(old).length(),all.length()); } //刪除以前的properties文件 CreatePro.deleteFile(filePath); //存儲新文件到以前位置 String[] arrPath = filePath.split("WEB-INF"); String path = arrPath[0]+"WEB-INF/configs"; CreatePro.saveFile(result, path, "xf.properties"); flag=true; } catch (IOException e) { e.printStackTrace(); flag=false; } return flag; } //讀properties文件,Properties方法 public static String readProperties(String filePath, String parameterName) { String value = ""; Properties prop = new Properties(); try { InputStream fis = new FileInputStream(filePath); prop.load(fis); value = prop.getProperty(parameterName); } catch (IOException e) { e.printStackTrace(); } return value; }?
這段代碼是極其有意義的,它非常全面的提供了Properties的修改操作,同時刪除了重復的鍵值。
?
總結
以上是生活随笔為你收集整理的java-- properties总结的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java读取properties配置文件
- 下一篇: SSL / TLS 协议运行机制详解