[英]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 );
否則,您可以編寫自己的比較器來執行自己的特定排序邏輯。 請查看此帖子以獲取更多示例/說明:
編輯
我相信您正在尋找這樣的東西。 請注意,為了對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.