使用java中的比较器对文件内容进行排序

时间:2014-11-27 10:16:17

标签: java list file sorting

我已经通过ArrayList添加了文件的内容,现在我需要对这些内容进行排序,然后将它们放回到文件中。我怎么能这样做?

package training;
import java.io.*;
import java.util.Collections;
/* method to create a file, store the contents of list and write read them back
*/

public class FileCreation implements Serializable {
    public void filesPatient(Person p) throws ClassNotFoundException {

        String Filename = "PatientDetails.txt";
        try {
            ObjectOutputStream os = new ObjectOutputStream(
                    new FileOutputStream(Filename));
            os.writeObject(p);
            os.close();
        } catch (Exception e) {

        }
        System.out.println("Done wRiting");
        try {
            ObjectInputStream is = new ObjectInputStream(new FileInputStream(
                    Filename));
            Person l = (Person) is.readObject();
            System.out.println("*****************Patient Details*************");
            System.out.println("Name : " + l.getName() + "\nID: " + l.getId()
                    + "\nGender: " + l.getGender());
            System.out.println();

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block

            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

请帮我找到合适的方法。

2 个答案:

答案 0 :(得分:1)

如果要按默认的字符串值排序对它们进行排序,可以使用Collections.sort方法:

Collections.sort( list );

否则,您可以编写自己的比较器来执行您自己的特定排序逻辑。有关更多示例/解释,请查看此帖子:

How to sort a Collection<T>?

修改

我相信你正在寻找这样的东西。注意为了对ArrayList进行排序,您必须将整个列表加载到内存中,然后对其进行排序,然后将整个列表写入文件,因此请确保您的列表不会太长并且适合内存。

ArrayList<Person> arrlist = new ArrayList<Person>(2);
while(more Person data exists) { // Replace this with however you are loading your data
    p = new Person();
    p.getdata();
    arrlist.add(p);
}

Collections.sort(arrList); // now your list is sorted

for(Person p : arrList) { 
    fc.filesPatient(p);  // add all your patients to file, from your list which is now sorted
}

答案 1 :(得分:0)

ArrayList<Person> arrlist = new ArrayList<Person>(2);
p = new Person();
p.getdata();
arrlist.add(p);
fc.filesPatient(p);

p = new Person();
p.getdata();
arrlist.add(p);
fc.filesPatient(p);