Java将文件中的内容读取到ArrayList(对象)
我可以使用PrintWriter将内容保存在ArrayList中,其中包含文件中的对象 宣布 但是现在我想再次将文件Java将文件中的内容读取到ArrayList(对象),java,arrays,arraylist,printwriter,Java,Arrays,Arraylist,Printwriter,我可以使用PrintWriter将内容保存在ArrayList中,其中包含文件中的对象 宣布 但是现在我想再次将文件userRecords中的内容读取到arrayList中,如何实现这一点 private static Boolean readObj(){ return true; } 另外,arrayList中的内容插入到程序中的某个点,因此arrayList不是空的。您无法按原样执行此操作。您甚至不需要声明一个可以稍后解析的toString()方法。最简单的方法是使用对象流 下面是
userRecords
中的内容读取到arrayList中,如何实现这一点
private static Boolean readObj(){
return true;
}
另外,arrayList中的内容插入到程序中的某个点,因此arrayList不是空的。您无法按原样执行此操作。您甚至不需要声明一个可以稍后解析的
toString()
方法。最简单的方法是使用对象流
下面是一些示例代码。我将数据写入base64编码的字符串,但您也可以轻松地将数据写入文件
// 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();
反向读取过程中的数据。查看
private static Boolean readObj(){
return true;
// 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();