list - To sort the contents of a file using comparator in java -


i have added contents of file through arraylist , need sort contents , put them on file. how can it?

package training; import java.io.*; import java.util.collections; /* method create file, store contents of list , write read them */  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 = 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 me find appropriate method it.

you use collections.sort method, if want sort them default string-value sort:

collections.sort( list ); 

otherwise can write own comparator own specific sorting logic. please check out post more examples / explanation:

how sort collection<t>?

edit

i believe looking this. note in order sort arraylist, have load entire list memory, sort it, write whole list file, make sure list not long , fit in memory.

arraylist<person> arrlist = new arraylist<person>(2); while(more person data exists) { // replace loading data     p = new person();     p.getdata();     arrlist.add(p); }  collections.sort(arrlist); // list sorted  for(person p : arrlist) {      fc.filespatient(p);  // add patients file, list sorted } 

Comments

Popular posts from this blog

matlab - "Contour not rendered for non-finite ZData" -

delphi - Indy UDP Read Contents of Adata -

javascript - Any ideas when Firefox is likely to implement lengthAdjust and textLength? -