[英]Java read contents from file into ArrayList (Objects)
我可以使用PrintWriter將內容保存在包含對象的ArrayList中,
public static ArrayList<AccountRecords> userRecords = new
ArrayList<AccountRecords>();
private static Boolean saveObj(){
try{
File userRecordsFile = new File("userRecords");
PrintWriter pw2 = new PrintWriter(new FileOutputStream(userRecordsFile));
for(int x=0;x<userRecords.size();x++){
pw2.println(userRecords.get(x));
}
pw2.close();
return true;
}catch(Exception e){
e.printStackTrace();
return true;
}
}
class AccountRecords{
private String identificationNo;
private int accountNo;
private int monthId;
private double balance;
private double credit;
private double debit;
private int year;
public AccountRecords(String identificationNo, int accNo,int monthId, double balance, double creditAmount, double debitAmount, int year){
this.identificationNo = identificationNo;
this.accountNo = accNo;
this.balance = balance;
this.monthId = monthId;
this.credit = creditAmount;
this.debit = debitAmount;
this.year = year;
}
public double getCredit() {
return credit;
}
public double getDebit() {
return debit;
}
public double getBalance() {
return balance;
}
public String getIdentificationNo() {
return identificationNo;
}
public int getAccountNo() {
return accountNo;
}
public int getMonthId() {
return monthId;
}
public int getYear() {
return year;
}
但是現在我想再次將文件userRecords
的內容讀入arrayList中,如何實現呢?
private static Boolean readObj(){
return true;
}
PS,將arrayList中的內容插入到程序中的某個點,因此arrayList不為空。
您無法原樣進行此操作。 您甚至沒有聲明稍后可以解析的toString()
方法。 最簡單的方法是使用對象流。
這是一些示例代碼。 我將數據寫入以64為基數的字符串,但是您也可以輕松地將數據寫入文件。
// Create a base 64 encoded string and print it
byte[] data = {-1,-2,-3,0,1,2,3,};
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream enc = new ObjectOutputStream( bos );
enc.writeObject( data );
enc.close();
String b64 = Base64.getEncoder().encodeToString( bos.toByteArray() );
System.out.println( "data=" + b64 );
// Read some base 64 encoded data and print it
String dataIn = "rO0ABXVyAAJbQqzzF/gGCFTgAgAAeHAAAAAH//79AAECAw==";
byte[] bdataIn = Base64.getDecoder().decode( dataIn );
ByteArrayInputStream bais = new ByteArrayInputStream( bdataIn );
ObjectInputStream ois = new ObjectInputStream( bais );
byte[] readData = (byte[]) ois.readObject();
System.out.println( "orig array: " + Arrays.toString( readData ) );
要編寫一個數組列表,只需編寫它:
OutputStream os = new FileOutputStream(userRecordsFile);
ObjectOutputStream enc = new ObjectOutputStream( os );
enc.writeObject( userRecords );
enc.close();
逆向過程以讀取數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.