public class Tast1 {
public static void main(String[] args) throws IOException {
List<Student> list = new ArrayList<>();
studenAdd(list);
objectFile(list);
}
public static void objectFile(List<Student> list)
throws FileNotFoundException, IOException {
FileOutputStream fos = new FileOutputStream("f:\\StudentInfo.txt");
System.out.println(list);
ObjectOutputStream oos = new ObjectOutputStream(fos);
for(Student st : list){
oos.writeObject(st);
}
oos.close();
}
public static void studenAdd(List<Student> list) {
list.add(new Student("张三", "男",25));
list.add(new Student("李四", "男",21));
list.add(new Student("张三", "男",25));
list.add(new Student("赵六", "男",23));
list.add(new Student("李思", "女",20));
list.add(new Student("李蕾", "女",19));
list.add(new Student("阿强", "男",30));
}
}
/*1.用代码实现以下需求
(1)定义学生类,包含姓名(String name),性别(String gender),年龄(int age)三个属性,生成空参有参构造,
set和get方法,toString方法
(2)键盘录入6个学员信息(录入格式:张三,男,25),要求有两个相同的信息,将6个学员信息存入到ArrayList集合中
(3)将存有6个学员信息的ArrayList集合对象写入到D:\\StudentInfo.txt文件中
(4)读取D:\\StudentInfo.txt文件中的ArrayList对象
(5)对ArrayList集合中的6个学生对象进行去重并按照年龄从小到大的顺序排序
(6)将ArrayList集合中排序后的结果利用PrintWriter流写入到E:\\StudentInfo.txt文件中(写入格式:张三-男-25)*/
public class Tast1_1 {
public static void main(String[] args) throws ClassNotFoundException, IOException {
List<Student> list = new ArrayList<>();
listAdd(list);
paiXu(list);
FileWriter fw = new FileWriter("f:\\StudentInfo1.txt");
PrintWriter pw = new PrintWriter(fw,true);
for(Student st :list){
String name = st.getName();
String gender = st.getGender();
int age = st.getAge();
pw.println(name+"-"+gender+"-"+age);
}
pw.close();
fw.close();
}
public static void paiXu(List<Student> list) {
int min = list.get(0).getAge();
Student st = null;
min = 0;
for (int i = 0; i < list.size(); i++) {
for (int j = 0; j < list.size(); j++) {
if(list.get(i).getAge() < list.get(j).getAge()){
st = list.get(i);
list.set(i,list.get(j));
list.set(j, st);
}
}
}
}
public static void listAdd(List<Student> list)
throws FileNotFoundException, IOException, ClassNotFoundException {
Set<Student> set = new HashSet<Student>();
FileInputStream fis = new FileInputStream("f:\\StudentInfo.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
Object obj = null;
Student st = (Student) obj;
while(fis.available()>0&&(st = (Student)ois.readObject()) != null){
//System.out.println(st);
boolean b = set.add(st);
if(b)
list.add(st);
}
ois.close();
//System.out.println(list);
} 作者: z873622900 时间: 2017-2-19 20:38