属性测试类--- Properties 以 键--值 存放方式
package com.softeem.len12;
import java.util.Enumeration;
import java.util.Properties;
public class PropertiesDemo {
public static void main(String[] args) {
//得到系统中属性的集合
Properties pro=System.getProperties();
// System.out.println(pro.getProperty("java.home"));
// System.out.println(pro.getProperty("os.name"));
// System.out.println(pro.getProperty("java.vendor"));
// System.out.println(pro.getProperty("java.version"));
// System.out.println(pro.getProperty("java.class.path"));
//返回一个枚举型对象(此对象里面保存了所有的key--键)
Enumeration en=pro.propertyNames();
//每一个键都对应一个值
while (en.hasMoreElements()) {//一直判断第一个
String key = (String)en.nextElement();//下一个键对象
System.out.print("键:"+key);
System.out.println("----》值:"+pro.getProperty(key));
// System.out.println("循环执行~~~");//不加nextElement(),程序成死循环
}
}
}
自定义属性
package com.softeem.len12;
import java.util.Properties;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
//自定义属性
public class PropertiesTest2 {
public static void main(String[] args) throws IOException{
//创建一个空的属性对象出来,里面什么属性都没有
Properties pro=new Properties();
//setProperty用于设置键和值
//设置值 键 值
// pro.setProperty("username", "小明");
// pro.setProperty("password", "123");
//输出值---getProperyt用于通过键来将值取出
// System.out.println(pro.getProperty("username"));
// System.out.println(pro.getProperty("password"));
//把系统盘中的文件内容载入到控制台输出
FileInputStream fis=new FileInputStream("C:\\我的文件夹\\Java\\文本文档.txt");
pro.load(fis);//将你指定的文件中的内容载入到pro对象中去
String name=pro.getProperty("username");
// String n=new String(name.getBytes("iso-8859-1"),"gbk");
// System.out.println(n);
System.out.println(Myutil.ChangeStr(name));
System.out.println(pro.getProperty("passworde"));
System.out.println(pro.getProperty("age"));
System.out.println(pro.getProperty("qq"));
System.out.println(pro.getProperty("tel"));
}
}
文件属性写入操作----store()
public class PropertiesTest {
public static void main(String[] args) {
Properties pro=new Properties();
//为pro对象设置属性值
pro.setProperty("username", "Tom");
pro.setProperty("password", "123");
pro.setProperty("Email", "91211@qq.com");
//将pro对象中的属性值写入到一个指定的文件中去
try {
//创建了一个文件输出字节流对象
out:特点(如果文件存在就写入,如果不存在就新建一个新的文件)
FileOutputStream out=newFileOutputStream("c:/456.txt",true);
//每一次执行程序,原来添加的数据就会被清空, 要想不被清空,需要加“true”
//将pro对象保存属性值写入到指定的文件中去
pro.store(out, "ke");
} catch (IOException e) {
e.printStackTrace();
}
}
}
//文件读取时,(如果有重复的key(值))每次都只是读取文件最后一次存入的信息。
转换中文乱码
package com.softeem.len12;
import java.io.UnsupportedEncodingException;
public class Myutil {
public static String ChangeStr(String param){
String msg="";//初始化
try {
msg = new String(param.getBytes("iso-8859-1"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return msg;
}
}