Java源码——对象序列化(对象的存储及读取)(Object Serialization)
2017-05-01 22:54
369 查看
代码如下:
1. 可序列化的实体类(Account)
2. 使用ObjectOutputStream将对象顺序写入文件
3. 使用ObjectInputStream类从文件中顺序读取对象
测试结果:
2.
Enter account number, first name, last name and balance.
Enter end-of-file indicator to end input.
? 103 huang pd 158.99
? 106 jiang sc 998.88
?
3.
Account First Name Last Name Balance
103 huang pd 158.99
106 jiang sc 998.88
No more records
1. 可序列化的实体类(Account)
// Fig. 15.9: Account.java // Serializable Account class for storing records as objects. package ch15; import java.io.Serializable; public class Account implements Serializable { private int account; private String firstName; private String lastName; private double balance; // initializes an Account with default values public Account() { this(0, "", "", 0.0); // call other constructor } // initializes an Account with provided values public Account(int account, String firstName, String lastName, double balance) { this.account = account; this.firstName = firstName; this.lastName = lastName; this.balance = balance; } // set account number public void setAccount(int acct) { this.account = account; } // get account number public int getAccount() { return account; } // set first name public void setFirstName(String firstName) { this.firstName = firstName; } // get first name public String getFirstName() { return firstName; } // set last name public void setLastName(String lastName) { this.lastName = lastName; } // get last name public String getLastName() { return lastName; } // set balance public void setBalance(double balance) { this.balance = balance; } // get balance public double getBalance() { return balance; } } // end class AccountRecordSerializable
2. 使用ObjectOutputStream将对象顺序写入文件
// Fig. 15.10: CreateSequentialFile.java // Writing objects sequentially to a file with class ObjectOutputStream. package ch15; import java.io.IOException; import java.io.ObjectOutputStream; import java.nio.file.Files; import java.nio.file.Paths; import java.util.NoSuchElementException; import java.util.Scanner; public class CreateSequentialFile { private static ObjectOutputStream output; // outputs data to file public static void main(String[] args) { openFile(); addRecords(); closeFile(); } // open file clients.ser public static void openFile() { try { output = new ObjectOutputStream( Files.newOutputStream(Paths.get("clients.ser"))); } catch (IOException ioException) { System.err.println("Error opening file. Terminating."); System.exit(1); // terminate the program } } // add records to file public static void addRecords() { Scanner input = new Scanner(System.in); System.out.printf("%s%n%s%n? ", "Enter account number, first name, last name and balance.", "Enter end-of-file indicator to end input."); while (input.hasNext()) // loop until end-of-file indicator { try { // create new record; this example assumes valid input Account record = new Account(input.nextInt(), input.next(), input.next(), input.nextDouble()); // serialize record object into file output.writeObject(record); } catch (NoSuchElementException elementException) { System.err.println("Invalid input. Please try again."); input.nextLine(); // discard input so user can try again } catch (IOException ioException) { System.err.println("Error writing to file. Terminating."); break; } System.out.print("? "); } } // close file and terminate application public static void closeFile() { try { if (output != null) output.close(); } catch (IOException ioException) { System.err.println("Error closing file. Terminating."); } } } // end class CreateSequentialFile
3. 使用ObjectInputStream类从文件中顺序读取对象
// Fig. 15.11: ReadSequentialFile.java // Reading a file of objects sequentially with ObjectInputStream // and displaying each record. package ch15; import java.io.EOFException; import java.io.IOException; import java.io.ObjectInputStream; import java.nio.file.Files; import java.nio.file.Paths; public class ReadSequentialFile { private static ObjectInputStream input; public static void main(String[] args) { openFile(); readRecords(); closeFile(); } // enable user to select file to open public static void openFile() { try // open file { input = new ObjectInputStream( Files.newInputStream(Paths.get("clients.ser"))); } catch (IOException ioException) { System.err.println("Error opening file."); System.exit(1); } } // read record from file public static void readRecords() { System.out.printf("%-10s%-12s%-12s%10s%n", "Account", "First Name", "Last Name", "Balance"); try { while (true) // loop until there is an EOFException { Account record = (Account) input.readObject(); // display record contents System.out.printf("%-10d%-12s%-12s%10.2f%n", record.getAccount(), record.getFirstName(), record.getLastName(), record.getBalance()); } } catch (EOFException endOfFileException) { System.out.printf("%nNo more records%n"); } catch (ClassNotFoundException classNotFoundException) { System.err.println("Invalid object type. Terminating."); } catch (IOException ioException) { System.err.println("Error reading from file. Terminating."); } } // end method readRecords // close file and terminate application public static void closeFile() { try { if (input != null) input.close(); } catch (IOException ioException) { System.err.println("Error closing file. Terminating."); System.exit(1); } } } // end class ReadSequentialFile
测试结果:
2.
Enter account number, first name, last name and balance.
Enter end-of-file indicator to end input.
? 103 huang pd 158.99
? 106 jiang sc 998.88
?
3.
Account First Name Last Name Balance
103 huang pd 158.99
106 jiang sc 998.88
No more records
相关文章推荐
- Java序列化对象的存储和读取
- Java —— 序列化对象的存储和读取
- Java对象序列化(Object Serialization)
- 存储两次序列化对象,读取报错问题 java.io.StreamCorruptedException: invalid type code: A
- Java序列化对象的存储和读取
- 使用Java序列化把对象存储到文件中,再从文件中读出来
- Java IO--对象序列化Serializable、ObjectOutputStream、ObjectInputStream、transient
- Java对象以Blob存储,及序列化反序列化 (1)
- .net序列化与反序列化——提供多次存储对象集后读取不完全解决方案
- Java的IO操作(三) - 对象的序列化、ObjectInputStream和ObjectOutputStream类
- Jedis存储Java对象--Java序列化为byte数组方式
- 使用Java序列化把对象存储到文件中,再从文件中读出来
- C#圣经读书笔记---CLR对象序列化(object serialization)
- flex socket.readObject() //flex读取java服务器端发送过来的对象
- .net序列化与反序列化——提供多次存储对象集后读取不完全解决方案
- Redis入门 – Jedis存储Java对象 - (Java序列化为byte数组方式)
- Serialize an object using XMLTag(s): XML(JAVA对象序列化成XML)
- Java 序列化对象存储
- Java对象以Blob存储,及序列化反序列化 (3)
- java 对象序列化与反序列化 FileInputSteam.readObject,writeObject