Java将文件中的内容读入ArrayList(Objects)

时间:2018-02-25 14:41:48

标签: java arrays arraylist printwriter

我能够使用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;
   }



  }

AccountRecords

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不为空。

1 个答案:

答案 0 :(得分:1)

你无法按原样做到这一点。您甚至不会声明可以在以后解析的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();

撤消进程以读取数据。