具体代码
//Student.java
package org.example.test016;
public class Student {
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
@Override
public String toString() {
return "学号: " + id + ",姓名: " + name + ",年龄: " + age;
}
public Student(String id, String name, String age) {
this.id = id;
this.name = name;
this.age = age;
}
private String id;
private String name;
private String age;
public static Student readString(String s) {
String[] text = s.split(",");
if (text.length == 3) {
return new Student(text[0], text[1], text[2]);
}
else {
throw new RuntimeException("读取信息出现问题~");
}
}
}
//Operator.java
package org.example.test016;
import java.io.*;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
public class Operator {
public static void main(String[] args) throws IOException {
File file = new File("F:\\Data\\softwareDesign\\softwareDesignTest002\\src\\main\\java\\org\\example\\test016\\Student.txt");
InputStream inputStream = new FileInputStream(file);
List<Student> list = getStudents(inputStream);
System.out.println("学号从小到大:");
Iterator<Student> iterator = list.iterator();
while (iterator.hasNext()) {
Student student = iterator.next();
System.out.println(student);
}
System.out.println("学号从大到小:");
ListIterator<Student> listIterator = list.listIterator();
for (listIterator = list.listIterator(); listIterator.hasNext();) {
listIterator.next();
}
for (; listIterator.hasPrevious();) {
Student student = listIterator.previous();
System.out.println(student);
}
}
public static List<Student> getStudents(InputStream inputStream) throws IOException {
List<Student> list = new LinkedList<>();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String text = null;
while ((text = bufferedReader.readLine()) != null) {
Student student = Student.readString(text);
list.add(student);
}
return list;
}
}
运行结果