K:java中properties文件的读写

Properties类与.properties文件:

  Properties类继承自Hashtable类并且实现了Map接口,也是使用一种键值对的形式来保存属性集的类,不过Properties有特殊的地方,就是它的键和值都是字符串类型。而.properties文件是由“键=值”的形式的数据项集合所构成的一个文件。需要注意的一点是.properties文件的数据项的键与值的信息显示的均是字符的编码的形式,在eclipse环境中,properties文件的默认编码格式是“ISO-8859-1”,properties文件的注释是采用"#"表示的

Properties类的主要方法:

  getProperty/setProperty: 这两个方法是分别是获取和设置属性信息。

  load(InputStream inStream): 从输入流中读取属性列表(键和元值素对)。并将其键与值的信息存入Properties对象中。

示例代码如下:

test.properties文件:
c=u680Bu62D0

示例代码:
package other;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

/**
 * 用于演示java中对于properties文件的读写
 * @author 学徒
 *
 */
public class PropertiesReadAndWrite
{
	public static void main(String[] args) throws IOException
	{
		//演示load方法
		File file=new File("test.properties");
		Properties properties=new Properties();
		FileInputStream in=new FileInputStream(file);
		properties.load(in);
		in.close();
		System.out.println(properties.getProperty("c"));
	}
}


运行结果:
栋拐

  store(OutputStream out, String comments): 将此 Properties表中的属性列表(键和值元素对)写入到输出流。如果comments不为空,保存后的属性文件第一行会是#comments,表示注释信息;如果为空则没有注释信息。注释信息后面是属性文件的当前保存时间信息。

示例代码如下:

test.properties文件:
c=u680Bu62D0

package other;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

/**
 * 用于演示java中对于properties文件的读写
 * @author 学徒
 *
 */
public class PropertiesReadAndWrite
{
	public static void main(String[] args) throws IOException
	{
		//用于演示store方法
		File file=new File("test.properties");
		FileOutputStream out=new FileOutputStream(file,true);//true表示追加信息到文件的
		out.write("
".getBytes());//为了用于将其与原有的信息进行划分开
		Properties properties=new Properties();
		properties.setProperty("a", "栋拐他老婆");
		properties.store(out, "~~哈哈哈,这是备注~~");
		out.close();
		System.out.println("OK!");
	}
}

运行结果:
OK!

代码执行后properties文件:
c=u680Bu62D0
#~~u54C8u54C8u54C8uFF0Cu8FD9u662Fu5907u6CE8~~
#Mon Dec 11 17:57:49 CST 2017
a=u680Bu62D0u4ED6u8001u5A46

回到目录|·(工)·)

原文地址:https://www.cnblogs.com/MyStringIsNotNull/p/8024362.html