可以通过下面代码的方式把一个Properties格式的文件放在电脑硬盘里:
<span style="font-size:18px;">package com.yunhe.shangwu;
// Properties的用法
// Map映射 集合下的子类 Hashtable 的子类 Properties的用法:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
public class PropertiesDemo1 {
public static void main(String[] args) {
Properties pro = new Properties();
pro.setProperty("CN", "中国");
pro.setProperty("US", "美国");
pro.setProperty("HH", "哈哈");
pro.setProperty("Dog", "小狗");
pro.setProperty("Cat", "小猫");
// 定义文件,输出到指定位置,如果不指定,默认输出到和src同级别的目录
File file = new File("C:\\Du.properties");
try {
// 定义一个文件输出流,(因为是从内存数据~File硬盘 所以是流出out)
// 将properties中的数据存储到输出流(文件)中
OutputStream out = new FileOutputStream(file);
// 可以编写一些注释 放进properties文件中
pro.store(out, "zhushi");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
</span>
通过代码方式读取硬盘里的文件
<span style="font-size:18px;">package com.yunhe.shangwu;
//通过代码的方式读取File硬盘中的properties文件
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
public class PropertiesDemo2 {
public static void main(String[] args) {
Properties pro = new Properties();
try {
// 从硬盘~内存 所以是流入 用input
InputStream inStream = new FileInputStream("C:\\Du.properties");
pro.load(inStream);
// 输出方式
Set<Entry<Object, Object>> entrySet = pro.entrySet();
for (Entry<Object, Object> temp : entrySet)
System.out.println(temp);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
</span>