流的分类
对于文本文件,选择带缓冲的字符流BufferedReader和BufferedWriter。
写文件的demo
private static void writeFile() {
// 写文件
File file = null;
BufferedWriter bw = null;
try {
String filePath = "demo" + File.separator + "abc.txt";
file = new File(filePath);
bw = new BufferedWriter(new FileWriter(file));
bw.write("zhangsan:24");
bw.newLine();
bw.write("lisi:26");
bw.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bw != null) {
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
读文件的demo
private static void readFile() {
// 读文件
File file = null;
BufferedReader br = null;
try {
String filePath = "demo" + File.separator + "abc.txt";
file = new File(filePath);
br = new BufferedReader(new FileReader(file));
String line=null;
while ((line=br.readLine())!=null){
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
properties文件
特别的,properties文件一般用于做配置文件。
properties继承于Hashtable,但有其特有的方法。
private static void properties1() {
//创建集合对象
Properties prop = new Properties();
//存储元素
prop.setProperty("zhangsan", "男");
prop.setProperty("lisi", "女");
prop.setProperty("wangwu", "男");
//遍历集合
Set<String> keySet = prop.stringPropertyNames();
for (String key : keySet) {
String value = prop.getProperty(key);
System.out.println(key + "," + value);
}
}
跟文件结合到一起。
写properties文件
private static void storeProperties() {
Properties prop = new Properties();
//存储元素
prop.setProperty("zhangsan", "男");
prop.setProperty("lisi", "女");
prop.setProperty("wangwu", "男");
String filePath = "demo" + File.separator + "abc.properties";
FileWriter fw = null;
try {
fw = new FileWriter(filePath);
prop.store(fw, null);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
读properties文件,用try-with-resource写
private static void loadProperties() {
Properties prop = new Properties();
String filePath = "demo" + File.separator + "abc.properties";
try {
FileReader fr = new FileReader(filePath); // 可能会抛FileNotFoundException
prop.load(fr); // 可能会抛IOException
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(prop);
}
properties文件
#Wed Mar 22 23:41:42 CST 2023
lisi=女
zhangsan=男
wangwu=男