導航:首頁 > 編程語言 > javaproperties注釋

javaproperties注釋

發布時間:2021-11-25 16:24:36

『壹』 java編程中Properties類的具體作用和使用!

如果不熟悉 java.util.Properties類,那麼現在告訴您它是用來在一個文件中存儲鍵-值對的,其中鍵和值是用等號分隔的。(如清單 1 所示)。最近更新的java.util.Properties 類現在提供了一種為程序裝載和存儲設置的更容易的方法: loadFromXML(InputStreamis) 和 storeToXML(OutputStream os, String comment) 方法。

一下是詳細的說明,希望能給大家帶來幫助。

清單 1. 一組屬性示例

foo=bar
fu=baz

將清單 1 裝載到 Properties 對象中後,您就可以找到兩個鍵( foo 和 fu )和兩個值( foo 的 bar 和 fu 的baz )了。這個類支持帶 \u 的嵌入 Unicode 字元串,但是這里重要的是每一項內容都當作 String 。

清單2 顯示了如何裝載屬性文件並列出它當前的一組鍵和值。只需傳遞這個文件的 InputStream 給 load()方法,就會將每一個鍵-值對添加到 Properties 實例中。然後用 list() 列出所有屬性或者用 getProperty()獲取單獨的屬性。

清單 2. 裝載屬性

import java.util.*;
import java.io.*;

public class LoadSample {
public static void main(String args[]) throws Exception {
Properties prop = new Properties();
FileInputStream fis =
new FileInputStream("sample.properties");
prop.load(fis);
prop.list(System.out);
System.out.println("\nThe foo property: " +
prop.getProperty("foo"));
}
}

運行 LoadSample 程序生成如清單 3 所示的輸出。注意 list() 方法的輸出中鍵-值對的順序與它們在輸入文件中的順序不一樣。Properties 類在一個散列表(hashtable,事實上是一個 Hashtable 子類)中儲存一組鍵-值對,所以不能保證順序。

清單 3. LoadSample 的輸出

-- listing properties --
fu=baz
foo=bar

The foo property: bar

XML 屬性文件
這里沒有什麼新內容。 Properties 類總是這樣工作的。不過,新的地方是從一個 XML 文件中裝載一組屬性。它的 DTD 如清單 4 所示。

清單 4. 屬性 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>

如果不想細讀 XML DTD,那麼可以告訴您它其實就是說在外圍 <properties> 標簽中包裝的是一個<comment> 標簽,後面是任意數量的 <entry> 標簽。對每一個 <entry>標簽,有一個鍵屬性,輸入的內容就是它的值。清單 5 顯示了 清單 1中的屬性文件的 XML 版本是什麼樣子的。

清單 5. XML 版本的屬性文件

<?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>

如果清單 6 所示,讀取 XML 版本的 Properties 文件與讀取老格式的文件沒什麼不同。

清單 6. 讀取 XML Properties 文件

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("\nThe foo property: " +
prop.getProperty("foo"));
}
}

關於資源綁定的說明
雖然 java.util.Properties 類現在除了支持鍵-值對,還支持屬性文件作為 XML 文件,不幸的是,沒有內置的選項可以將ResourceBundle 作為一個 XML 文件處理。是的, PropertyResourceBundle 不使用 Properties對象來裝載綁定,不過裝載方法的使用是硬編碼到類中的,而不使用較新的 loadFromXML() 方法。

運行清單 6 中的程序產生與原來的程序相同的輸出,如 清單 2所示。

保存 XML 屬性
新的 Properties 還有一個功能是將屬性存儲到 XML 格式的文件中。雖然 store() 方法仍然會創建一個類似 清單 1所示的文件,但是現在可以用新的 storeToXML() 方法創建如 清單 5 所示的文件。只要傳遞一個 OutputStream和一個用於注釋的 String 就可以了。清單 7 展示了新的 storeToXML() 方法。

清單 7. 將 Properties 存儲為 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");
fos.close();
}
}

運行清單 7 中的程序產生的輸出如清單 8 所示。

清單 8. 存儲的 XML 文件

<?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>
在這里改了一個例子:
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* 實現properties文件的讀取
* @author haoxuewu
*/
public class Test {
public static void main(String[] args) {
try {
long start = System.currentTimeMillis();
InputStream is = new FileInputStream("conf.properties");
Properties p = new Properties();
p.load(is);
is.close();
System.out.println("SIZE : " + p.size());
System.out.println("homepage : " + p.getProperty("homepage"));
System.out.println("author : " + p.getProperty("author"));
System.out.println("school : " + p.getProperty("school"));
long end = System.currentTimeMillis();
System.out.println("Cost : " + (end - start));
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
} conf.properties
# Configuration file
homepage = http://www.blogjava.net/haoxuewu
author = bbflyerwww
school = jilinjianzhugongchengxueyuan
Result
SIZE:3
homepage : http://www.blogjava.net/haoxuewu
author : bbflyerwww
school : jilinjianzhugongchengxueyuan

Cost : 0

『貳』 如何更改java.properties注釋亂碼

修改文件編碼utf-8、gb2312,找到不亂的那個,剪切,改回原來的編碼,粘貼

『叄』 java的properties文件,輸入中文顯示ascii

properties文件是這么復寫的嗎。制。,應該是key=value行式的吧。注釋則是開頭用'#'井號

比如

### valid values are: true, false (true is the default)

struts.objectFactory.spring.useClassCache = true

另外,在屬性文件中是不能寫入中文的,即使寫入了中文,讀出來的也是亂碼(注釋除外,注釋是給人看的,不是讓程序來讀的)。而你之所以寫進去的中文自動轉成了Unicode編碼,可能是用eclipse的properties editor的添加編輯界面添加導致的(如下圖),該界面本來就是增加屬性文件的屬性用的。如果是要加註釋,需點擊下面的source標簽,切換到文本編輯模式,在要加註釋的項之前插入一行,首字元為'#',然後輸入你的中文注釋即可

『肆』 java web程序註解讀取properties文件,每次修改都需要重啟伺服器,怎麼解決

你是不是用了類似maven的管理工具
然後修改的是src下面的,target也要修改才行

『伍』 JAVA properties保留空白行與注釋

/*
* Converts unicodes to encoded \uxxxx and writes out any of the
* characters in specialSaveChars with a preceding slash
*/
private String saveConvert(String theString, boolean escapeSpace) {
int len = theString.length();
StringBuffer outBuffer = new StringBuffer(len * 2);

for (int x = 0; x < len; x++) {
char aChar = theString.charAt(x);
switch (aChar) {
case ' ':
if (x == 0 || escapeSpace)
outBuffer.append('\\');

outBuffer.append(' ');
break;
case '\\':
outBuffer.append('\\');
outBuffer.append('\\');
break;
case '\t':
outBuffer.append('\\');
outBuffer.append('t');
break;
case '\n':
outBuffer.append('\\');
outBuffer.append('n');
break;
case '\r':
outBuffer.append('\\');
outBuffer.append('r');
break;
case '\f':
outBuffer.append('\\');
outBuffer.append('f');
break;
default:
if ((aChar < 0x0020) || (aChar > 0x007e)) {
outBuffer.append('\\');
outBuffer.append('u');
outBuffer.append(toHex((aChar >> 12) & 0xF));
outBuffer.append(toHex((aChar >> 8) & 0xF));
outBuffer.append(toHex((aChar >> 4) & 0xF));
outBuffer.append(toHex(aChar & 0xF));
} else {
if (specialSaveChars.indexOf(aChar) != -1)
outBuffer.append('\\');
outBuffer.append(aChar);
}
}
}
return outBuffer.toString();
}

/**
* Convert a nibble to a hex character
*
* @param nibble
* the nibble to convert.
*/
private static char toHex(int nibble) {
return hexDigit[(nibble & 0xF)];
}

/** A table of hex digits */
private static final char[] hexDigit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E',
'F' };

public synchronized Object put(Object key, Object value) {
context.putOrUpdate(key.toString(), value.toString());
return super.put(key, value);
}

public synchronized Object put(Object key, Object value, String line) {
context.putOrUpdate(key.toString(), value.toString(), line);
return super.put(key, value);
}

public synchronized Object remove(Object key) {
context.remove(key.toString());
return super.remove(key);
}

class PropertiesContext {
private List commentOrEntrys = new ArrayList();

public List getCommentOrEntrys() {
return commentOrEntrys;
}

public void addCommentLine(String line) {
commentOrEntrys.add(line);
}

public void putOrUpdate(PropertyEntry pe) {
remove(pe.getKey());
commentOrEntrys.add(pe);
}

public void putOrUpdate(String key, String value, String line) {
PropertyEntry pe = new PropertyEntry(key, value, line);
remove(key);
commentOrEntrys.add(pe);
}

public void putOrUpdate(String key, String value) {
PropertyEntry pe = new PropertyEntry(key, value);
int index = remove(key);
commentOrEntrys.add(index,pe);
}

public int remove(String key) {
for (int index = 0; index < commentOrEntrys.size(); index++) {
Object obj = commentOrEntrys.get(index);
if (obj instanceof PropertyEntry) {
if (obj != null) {
if (key.equals(((PropertyEntry) obj).getKey())) {
commentOrEntrys.remove(obj);
return index;
}
}
}
}
return commentOrEntrys.size();
}

class PropertyEntry {
private String key;

private String value;

private String line;

public String getLine() {
return line;
}

public void setLine(String line) {
this.line = line;
}

public PropertyEntry(String key, String value) {
this.key = key;
this.value = value;
}

/**
* @param key
* @param value
* @param line
*/
public PropertyEntry(String key, String value, String line) {
this(key, value);
this.line = line;
}

public String getKey() {
return key;
}

public void setKey(String key) {
this.key = key;
}

public String getValue() {
return value;
}

public void setValue(String value) {
this.value = value;
}

public String toString() {
if (line != null) {
return line;
}
if (key != null && value != null) {
String k = saveConvert(key, true);
String v = saveConvert(value, false);
return k + "=" + v;
}
return null;
}
}
}

/**
* @param comment
*/
public void addComment(String comment) {
if (comment != null) {
context.addCommentLine("#" + comment);
}
}

}

『陸』 怎樣在.properties文件中注釋

1、打開IDEA,新建一個Web項目,右鍵點擊新建的項目名,選擇創建文件目錄(Directory),一般properties文件夾命名應為resoures。

『柒』 JAVA properties保留注釋

public class SafeProperties extends Properties {
private static final long serialVersionUID = 5011694856722313621L;

private static final String keyValueSeparators = "=: \t\r\n\f";

private static final String strictKeyValueSeparators = "=:";

private static final String specialSaveChars = "=: \t\r\n\f#!";

private static final String whiteSpaceChars = " \t\r\n\f";

private PropertiesContext context = new PropertiesContext();

public PropertiesContext getContext() {
return context;
}

public synchronized void load(InputStream inStream) throws IOException {

BufferedReader in;

in = new BufferedReader(new InputStreamReader(inStream, "8859_1"));
while (true) {
// Get next line
String line = in.readLine();
// intract property/comment string
String intactLine = line;
if (line == null)
return;

if (line.length() > 0) {

// Find start of key
int len = line.length();
int keyStart;
for (keyStart = 0; keyStart < len; keyStart++)
if (whiteSpaceChars.indexOf(line.charAt(keyStart)) == -1)
break;

// Blank lines are ignored
if (keyStart == len)
continue;

// Continue lines that end in slashes if they are not comments
char firstChar = line.charAt(keyStart);

if ((firstChar != '#') && (firstChar != '!')) {
while (continueLine(line)) {
String nextLine = in.readLine();
intactLine = intactLine + "\n" + nextLine;
if (nextLine == null)
nextLine = "";
String loppedLine = line.substring(0, len - 1);
// Advance beyond whitespace on new line
int startIndex;
for (startIndex = 0; startIndex < nextLine.length(); startIndex++)
if (whiteSpaceChars.indexOf(nextLine.charAt(startIndex)) == -1)
break;
nextLine = nextLine.substring(startIndex, nextLine.length());
line = new String(loppedLine + nextLine);
len = line.length();
}

// Find separation between key and value
int separatorIndex;
for (separatorIndex = keyStart; separatorIndex < len; separatorIndex++) {
char currentChar = line.charAt(separatorIndex);
if (currentChar == '\\')
separatorIndex++;
else if (keyValueSeparators.indexOf(currentChar) != -1)
break;
}

// Skip over whitespace after key if any
int valueIndex;
for (valueIndex = separatorIndex; valueIndex < len; valueIndex++)
if (whiteSpaceChars.indexOf(line.charAt(valueIndex)) == -1)
break;

// Skip over one non whitespace key value separators if any
if (valueIndex < len)
if (strictKeyValueSeparators.indexOf(line.charAt(valueIndex)) != -1)
valueIndex++;

// Skip over white space after other separators if any
while (valueIndex < len) {
if (whiteSpaceChars.indexOf(line.charAt(valueIndex)) == -1)
break;
valueIndex++;
}
String key = line.substring(keyStart, separatorIndex);
String value = (separatorIndex < len) ? line.substring(valueIndex, len) : "";

// Convert then store key and value
key = loadConvert(key);
value = loadConvert(value);
//memorize the property also with the whold string
put(key, value, intactLine);
} else {
//memorize the comment string
context.addCommentLine(intactLine);
}
} else {
//memorize the string even the string is empty
context.addCommentLine(intactLine);
}
}
}

/*
* Converts encoded \uxxxx to unicode chars and changes special saved
* chars to their original forms
*/
private String loadConvert(String theString) {
char aChar;
int len = theString.length();
StringBuffer outBuffer = new StringBuffer(len);

for (int x = 0; x < len;) {
aChar = theString.charAt(x++);
if (aChar == '\\') {
aChar = theString.charAt(x++);
if (aChar == 'u') {
// Read the xxxx
int value = 0;
for (int i = 0; i < 4; i++) {
aChar = theString.charAt(x++);
switch (aChar) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
value = (value << 4) + aChar - '0';
break;
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
value = (value << 4) + 10 + aChar - 'a';
break;
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
value = (value << 4) + 10 + aChar - 'A';
break;
default:
throw new IllegalArgumentException("Malformed \\uxxxx encoding.");
}
}
outBuffer.append((char) value);
} else {
if (aChar == 't')
outBuffer.append('\t'); /* ibm@7211 */

else if (aChar == 'r')
outBuffer.append('\r'); /* ibm@7211 */
else if (aChar == 'n') {
/*
* ibm@8897 do not convert a \n to a line.separator
* because on some platforms line.separator is a String
* of "\r\n". When a Properties class is saved as a file
* (store()) and then restored (load()) the restored
* input MUST be the same as the output (so that
* Properties.equals() works).
*
*/
outBuffer.append('\n'); /* ibm@8897 ibm@7211 */
} else if (aChar == 'f')
outBuffer.append('\f'); /* ibm@7211 */
else
/* ibm@7211 */
outBuffer.append(aChar); /* ibm@7211 */
}
} else
outBuffer.append(aChar);
}
return outBuffer.toString();
}

public synchronized void store(OutputStream out, String header) throws IOException {
BufferedWriter awriter;
awriter = new BufferedWriter(new OutputStreamWriter(out, "8859_1"));
if (header != null)
writeln(awriter, "#" + header);
List entrys = context.getCommentOrEntrys();
for (Iterator iter = entrys.iterator(); iter.hasNext();) {
Object obj = iter.next();
if (obj.toString() != null) {
writeln(awriter, obj.toString());
}
}
awriter.flush();
}

private static void writeln(BufferedWriter bw, String s) throws IOException {
bw.write(s);
bw.newLine();
}

private boolean continueLine(String line) {
int slashCount = 0;
int index = line.length() - 1;
while ((index >= 0) && (line.charAt(index--) == '\\'))
slashCount++;
return (slashCount % 2 == 1);
}

『捌』 java的properties文件中文亂碼

properties中出現亂碼說明文件的編碼格式不對。

解決方案:

第一步:在文件上右擊,選擇」專properties「;

第二屬步:選擇」resource「,之後更改編碼格式為」UTF-8「,點擊」ok「完成設置。

備註:如果改為此編碼格式不行,選擇other,之後選擇GBK、GB2312,肯定是可以的。

『玖』 JAVA的properties類的save()方法在保存文件的時候,配置的中文注釋會消除掉,如何讓中文注釋保留呢。

Java內置的Properties類就是有這個問題,我推薦你使用Apache的Commens類庫,裡面有一個操作Properties的類是可以保留注釋的,很方便

閱讀全文

與javaproperties注釋相關的資料

熱點內容
u盤拷貝文件以後為空 瀏覽:917
快雲主機資料庫連接方法 瀏覽:756
javagsp定位 瀏覽:384
jsp頁面表格導出excel 瀏覽:976
imagetest教程 瀏覽:244
怎樣將一個cad文件包圖紙兼容 瀏覽:898
論文有什麼好的網站 瀏覽:581
jdk7javadoc 瀏覽:687
編程小游戲是如何設計的 瀏覽:913
網路安全風險案例 瀏覽:46
司法考試哪個網站好 瀏覽:469
android搜索功能代碼 瀏覽:437
文件名如何沒有文字 瀏覽:601
吃雞地圖資源包文件路徑 瀏覽:267
cad文件轉移手機 瀏覽:733
指定區域網內文件delphi 瀏覽:638
蘋果5s充電介面維修 瀏覽:913
建行app怎麼老是信息填寫錯誤 瀏覽:832
羅技g903切換配置文件 瀏覽:649
游戲的數據在哪個英文文件夾 瀏覽:435

友情鏈接