2021-09-20 IO流(Properties存取配置文件)
2021-10-11 本文已影响0人
Denholm
演示如何将流中的数据存储到集合中,想要将info.txt中的数据存到集合中进行操作
1.用一个流和info.txt文件关联
2.读取一行数据,将该行数据用“=”进行切割
3.等号左边作为键,右边作为值,存入到Properties集合中即可
import java.io.*;
import java.util.Properties;
public class PropertiesDemo2 {
public static void main(String[] args) throws Exception {
// method();
loadDemo();
}
public static void method() throws IOException {
BufferedReader bufr = new BufferedReader(new FileReader("E:\\info.txt"));
String line;
Properties prop = new Properties();
while ((line = bufr.readLine()) != null) {
String[] arr = line.split("=");
System.out.println(arr[0] + "..." + arr[1]);
prop.setProperty(arr[0], arr[1]);
}
bufr.close();
System.out.println(prop);
}
public static void loadDemo() throws IOException {
Properties prop = new Properties();
FileInputStream fis = new FileInputStream("E:\\info.txt");
// 将流中的数据加载进集合
prop.load(fis);
prop.setProperty("wangwu", "35");
FileOutputStream fos = new FileOutputStream("E:\\info.txt");
prop.store(fos, "haha");
System.out.println(prop);
prop.list(System.out);
fis.close();
fos.close();
}
}