导航:首页 > 编程语言 > 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注释相关的资料

热点内容
三星电视拆机教程 浏览:19
创维怎么连接网络 浏览:868
2007版word绘图在哪里 浏览:311
可以拍车牌的app是什么 浏览:508
文件加个井字号什么意思 浏览:155
怎么删除多重网络 浏览:999
求生之路2局域网联机工具 浏览:827
说明文件结尾用什么词 浏览:578
发送的文件名变数字 浏览:778
档案数据库管理 浏览:992
微信acl是金融传销吗 浏览:620
企业如何通过进行网络营销 浏览:551
微信json转换错误 浏览:364
拉勾勾是什么网站 浏览:556
长沙哪个学校有大数据技术与应用 浏览:137
qq语音停止运行 浏览:312
java获取系统当前时间并转为秒 浏览:679
linux目录文件数 浏览:994
ug如何用宏编程 浏览:857
在编程中P代表什么 浏览:420

友情链接