简体   繁体   中英

To sort the contents of a file using comparator in java

I have added the contents of a file through an ArrayList and now I need to sort those contents and then put them back on the file. how can I do it?

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();
        }
    }

}

Please help me find an appropriate method to do it.

You could use the Collections.sort method, if you want to sort them by the default String-value sort:

Collections.sort( list );

Otherwise you can write your own comparator to do your own specific sorting logic. Please check out this post for more examples / explanation:

How to sort a Collection<T>?

EDIT

I believe you are looking for something like this. Note in order to sort an ArrayList, you will have to load the entire list into memory, then sort it, then write the whole list to file, so make sure your list is not too long and will fit in memory.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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