集合倒序排序存入文件中并读取出来
先建立一个Person类:
package com.lanqiao.javatest;
import java.io.Serializable;
public class Person implements Comparable,Serializable{
private String name;
private int age;
public Person() {
super();
}
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
@Override
public int compareTo(Object o) {
Person input=(Person)o;
int res=age>input.age?-1:(age==input.age?0:1);
if(res==0){
res=name.compareTo(input.name);
}
return res;
}
}
建立一个测试类:
package com.lanqiao.javatest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Array;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class Test3 {
private static final List<Person> Person = null;
static File file=new File("File.txt");
static List<Person> list=new ArrayList<Person>();
@SuppressWarnings("unchecked")
public static void ru() throws IOException{//将数据写入集合中
Person[] person=new Person[5];
for(int i=0;i<5;i++){
person[0]=new Person("jlrt",23);
person[1]=new Person("jlr",54);
person[2]=new Person("jldasdas",90);
person[3]=new Person("jlds",12);
person[4]=new Person("jldas",14);
list.add(person[i]);
Collections.sort(list);
}
}
public static void writer() throws IOException{//集合中的数据写入文件
ObjectOutputStream oos=null;
try {
oos=new ObjectOutputStream(new FileOutputStream(file));
oos.writeObject(list);
oos.flush();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(oos!=null){
oos.close();
}
}
}
@SuppressWarnings("unchecked")
public static ArrayList<Person> read() throws Exception{//从文件中将数据读取到集合中
ObjectInputStream ois=null;
ArrayList<Person> ll=null;
try {
ois=new ObjectInputStream(new FileInputStream(file));
ll=new ArrayList<Person>();
ll=(ArrayList<Person>)ois.readObject();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(ois!=null){
ois.close();
}
}
return ll;
}
public static void main(String[] args) throws Exception {
System.out.println("-------------------------------------------");
ru();
writer();
ArrayList<Person> ll=read();//建立一个集合承接read()方法中的数据
for(int i=0;i<ll.size();i++){
System.out.println(ll.get(i).toString());
}
System.out.println("-------------------------------------------");
}
}
另外还有建立以文件(名字为:File.txt);