IO流将数据保存到本地
可以遍历数组,遍历集合将里面的数据通过IO流写入txt.
若要拿到数据,可以将txt中的元素读入一行,Bufferedreader中的特有方法 readline().或按字符读入,缓冲区读入.
https://blog.csdn.net/qq_43371004/article/details/86513355
案例:
将学生的成绩输入按照总分高低排序,并存到txt文本文件中
学生类:
成员变量:姓名,语文成绩,数学成绩,英语成绩
提供get和set方法,提供总分方法
package com.westos.Demo;
public class Student {
private String name;
private int chineseScore;
private int mathScore;
private int englishScore;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getChineseScore() {
return chineseScore;
}
public void setChineseScore(int chineseScore) {
this.chineseScore = chineseScore;
}
public int getMathScore() {
return mathScore;
}
public void setMathScore(int mathScore) {
this.mathScore = mathScore;
}
public int getEnglishScore() {
return englishScore;
}
public void setEnglishScore(int englishScore) {
this.englishScore = englishScore;
}
public int getTotalScore() {
return chineseScore + mathScore + englishScore;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", chineseScore=" + chineseScore +
", mathScore=" + mathScore +
", englishScore=" + englishScore +
'}';
}
}
测试类:
package com.westos.Demo;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Comparator;
import java.util.Scanner;
import java.util.TreeSet;
public class Demo1 {
public static void main(String[] args) throws IOException {
//将学生的成绩按照总分排列,存到txt中
TreeSet<Student> set= new TreeSet<>(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
int num =o1.getTotalScore()-o2.getTotalScore();
int num2=num==0?o1.getName().compareTo(o2.getName()):num;
return num2;
}
});
Scanner sc = new Scanner(System.in);
for (int i = 1; i <= 3; i++) {
Student student = new Student();
System.out.println("请输入第" + i + "个学生的姓名");
String name = sc.nextLine();
student.setName(name);
System.out.println("请输入第" + i + "个学生的语文成绩");
int chineseScore = Integer.parseInt(sc.nextLine());
student.setChineseScore(chineseScore);
System.out.println("请输入第" + i + "个学生的数学成绩");
int mathScore = Integer.parseInt(sc.nextLine());
student.setMathScore(mathScore);
System.out.println("请输入第" + i + "个学生的英语成绩");
int englishScore = Integer.parseInt(sc.nextLine());
student.setEnglishScore(englishScore);
//再把学对象存到集合中
set.add(student);
}
BufferedWriter out = new BufferedWriter(new FileWriter("studentScore.txt",true));
out.write("序号\t\t"+"姓名\t\t"+"语文成绩\t"+"数学成绩\t"+"英语成绩\t"+"总分");
out.newLine();
out.flush();
//遍历集合把数据存到文本文件中去
int index=1;
for (Student student : set) {
out.write((index++)+"\t\t"+student.getName()+"\t\t"+student.getChineseScore()+"\t\t"+student.getMathScore()+"\t\t"+student.getEnglishScore()+"\t\t"+student.getTotalScore());
out.newLine();
out.flush();
}
out.close();
}
}
谢谢!