繁体   English   中英

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

[英]To sort the contents of a file using comparator in java

我已经通过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();
        }
    }

}

请帮助我找到合适的方法。

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

Collections.sort( list );

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

如何对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
}
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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM