0
如何從文件中讀取文件數據/反序列化對象。我創建了一個二進制文件文件,其中包含公司數據列表,我可以添加新公司及其相關數據,但是何時我想讀回的所有文件DATAS它只給人的第一家公司DATAS和它打印空..what低於這個問題是我做了什麼反序列化對象只讀取一個數據
public class CompanyInfo extends Company {
int counter=0;
Scanner in=new Scanner(System.in);
private ArrayList<Company> companyinfo;
public CompanyInfo() {
companyinfo=new ArrayList<Company>();
}
public void registercompany() {
System.out.println("Enter Company Name \n");
companyName=in.nextLine();
System.out.println("\n");
System.out.println("Enter Company Code \n");
companyCode=in.nextLine();
System.out.println("\n");
System.out.println("Enter the Share Number \n");
shareNo=in.nextInt();
System.out.println("\n");
System.out.println("Enter Closing Rate \n");
closingRate=in.nextDouble();
Company cin=new Company(companyName,companyCode,shareNo,closingRate);
companyinfo.add(cin);
try {
ObjectOutputStream outObjFile =new ObjectOutputStream(new FileOutputStream("companies.dat",true));
Company company = new Company(companyName,companyCode,shareNo,closingRate);
outObjFile.writeObject(company);
outObjFile.writeChars("\n");
outObjFile.close();
} catch (Exception e) {
// TODO: handle exception
System.out.println("A file error has occurred. Sorry.");
System.out.println(e.getMessage());
}
counter++;
}
public void viewcompany(){
try {
ObjectInputStream inObjFile = new ObjectInputStream(
new FileInputStream("companies.dat"));
System.out.println(inObjFile.readObject()); // displays first object
Company company = (Company)inObjFile.readObject(); // restores object
System.out.println(company); // displays restored object
inObjFile.close(); // finished with the file now.
} catch (Exception e) {
System.out.println(e.getMessage());
}
你只序列化/反序列化的公司,如果你想獲得所有的人,你應該序列化/反序列化'companyinfo' –
我沒有得到你對不起!你能解釋一下嗎? –
我猜''append = true'標誌到'FileOutputStream',可能會試圖將每個寫入值附加到文件。但是,ObjectOutputStream將特殊的標記值寫入流中,因此如果要從一個文件中讀取多個單獨的對象流,則必須做更多的工作。 –