我輸入客戶詳細信息並將其保存到文件中。當我打印出來時,只有第一位客戶正在打印。爲什麼會發生這種情況,我該如何解決?JAVA:嘗試輸出一組客戶,但僅打印第一個客戶
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
Customer e = new Customer();
Scanner scan = new Scanner(System.in);
System.out.println("");
e.setCustID(scan.nextLong());
e.setName(scan.next());
e.setSurname(scan.next());
try {
FileOutputStream fileOut = new FileOutputStream(new File("customer.txt"),true);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in /tmp/employee.ser\n\n");
}catch(IOException i) {
i.printStackTrace();
}
try {
FileInputStream fileIn = new FileInputStream("customer.txt");
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (Customer) in.readObject();
in.close();
fileIn.close();
}catch(IOException i) {
i.printStackTrace();
return;
}catch(ClassNotFoundException c) {
System.out.println("Customer class not found");
c.printStackTrace();
return;
}
File file = new File("customer.txt");
if(file.exists()) {
StringBuilder inputStringBuilder = new StringBuilder();
FileInputStream fileReader = new FileInputStream(file);
BufferedReader buffReader = new BufferedReader(new InputStreamReader(fileReader, "UTF-8"));
String line = buffReader.readLine();
while(line != null) {
System.out.print(e.getCustID()+"\t");
System.out.print(e.getName()+"\t");
System.out.print(e.getSurname()+"\n");
line=buffReader.readLine();
}
//if line is null, we have reached EOF (end of file)
buffReader.close();
}
else {
System.out.println("File not found!");
}
System.out.println("Deserialized Employee...");
System.out.println("Name: " + e.getCustID());
System.out.println("Address: " + e.getName());
System.out.println("SSN: " + e.getSurname());
// http://www.tutorialspoint.com/java/java_serialization.htm
// to try http://www.w3resource.com/java-tutorial/writing-the-file.php
}
}
用「而((行= buffReader.readLine())!= NULL)」只閱讀文本文件的每一行的第一個條目。但是在每一行中都有多個條目並且輸入是序列化的 –
是正確寫入file.com的數據嗎? –
文件中的數據示例:¬ísr Customer÷w¬; RZ + L Namet Ljava/lang/String; L Surnameq〜 –