前一篇讲了文件的字符输入输出流,但是最终还是要一个字符一个字符的读取和写入。缓存式的字符输入输出流BufferedReader BufferedWriter里面有方法是按照一行一行的进行读和写的。
一、BufferedReader
实体类:
package io.buffer;
public class StudentInfo {
private String name;
private String stuNo;
private String claName;
public StudentInfo( String name,String stuNo, String claName) {
this.name=name;
this.stuNo=stuNo;
this.claName=claName;
}
public String getStuNo() {
return stuNo;
}
public void setStuNo(String stuNo) {
this.stuNo = stuNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getClaName() {
return claName;
}
public void setClaName(String claName) {
this.claName = claName;
}
@Override
public String toString() {
return name+","+stuNo+","+claName;
}
}
操作类:
package io.buffer;
import java.io.*;
import java.util.*;
public class StudentInfoReader {
public static void main(String[] args) {
//String path = FileReader.class.getResource("/").getFile();
String fileName = "F:" + File.separator + "test.txt";
List<StudentInfo> stuls =readStudentInfo(fileName);
System.out.println(stuls.size());
}
public static List<StudentInfo> readStudentInfo(String fileName) {
List<StudentInfo> list = new ArrayList<StudentInfo>();
try {
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = null;
while ( (line = br.readLine()) != null ) {
String[] infos = line.split(",");
list.add(new StudentInfo(infos[0], infos[1], infos[2]));
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
}
二、BufferedWriter。BufferedWrite比普通的字符流会多一个插入分行符的方法:newLine()写入一个行分隔符。下面读取test.txt中的数据并封装为StudengInfo:
package io.buffer;
import java.io.*;
import java.util.*;
public class StudentInfoReader1 {
public static void main(String[] args) {
String fileName = "F:" + File.separator + "test.txt";
StudentInfo student=new StudentInfo("Lily","100003","java");
addStudentInfo(fileName,student);
List<StudentInfo> stuls =readStudentInfo(fileName);
System.out.println(stuls.size());
}
public static List<StudentInfo> readStudentInfo(String fileName) {
List<StudentInfo> list = new ArrayList<StudentInfo>();
try {
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = null;
while ( (line = br.readLine()) != null ) {
String[] infos = line.split(",");
list.add(new StudentInfo(infos[0], infos[1], infos[2]));
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
public static void addStudentInfo(String fileName,StudentInfo student) {
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(fileName,true));
bw.write("\r\n");//相当于bw.newLine();
bw.write(student.toString());
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}