我用一个
Student
实体类作为存储容器:JavaBean.png
结果:
读取txt文件.png
大致思路:
一次读一行, 使用BufferedReader
的readLine()
, 然后利用中间的空格来截取, 分段读取到变量:
// 从文本文件中读,将读出的数据存放于集合中
List<Student> list = new ArrayList<>();
File file = new File(fileName);
try {
BufferedReader bf = new BufferedReader(new FileReader(file));
String content = "";
while (content != null) {
content = bf.readLine();
if (content == null) {
break;
}
// 设置正则将多余空格或Tab键都转为一个空格
String[] str = content.trim().split("\\s{2,}|\t");
Student student = new Student();
student.setId(str[0]);
student.setName(str[1]);
student.setGender(str[2]);
student.setJava(Float.parseFloat(str[3]));
student.setEnglish(Float.parseFloat(str[4]));
student.setMath(Float.parseFloat(str[5]));
student.setTotalScore();
student.setAverage();
list.add(student);
}
bf.close();
} catch (IOException e) {
e.printStackTrace();
}
写入txt文件
思路: 使用打印流PrintStream
的printf()
格式化输出.
// 将集合中的数据写入到txt文件中, 思路: 使用打印流
public void WriteTxt(List<Student> list, String fileName) {
try {
PrintStream printStream = new PrintStream(new FileOutputStream(fileName));
printStream.printf("学号\t姓名\t性别\t总分\t平均分\n");
for (int i = 0; i < list.size(); i++) {
printStream.printf("%s\t%s\t%s\t%.2f\t%.2f\n", list.get(i).getId(),
list.get(i).getName(), list.get(i).getGender(),
list.get(i).getTotalScore(), list.get(i).getAverage());
}
printStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
如需要, 完整代码下载地址:
https://github.com/menglanyingfei/Java/blob/master/CodeCollection/JavaSEProjects/excelIo/excelIo.zip
网友评论