我有一個很大的問題,我在一個txt文件中寫入相同的對象帳戶當我點擊查看所有對象我已經寫在TXT是隻顯示我最後一個,在JOptionPane中顯示帳戶,第二個是我如何使帳戶採取一,二,三......每個帳戶,我寫了一個數字加一先前帳戶。 我believ解釋清楚爲什麼給我看最後一個對象,我把它放在TXT
if(str.equals("Receipt"))
{
ObjectInputStream in = null;
Account acc = null;
try
{
in = new ObjectInputStream(new FileInputStream("Accounts.txt"));
while((acc = (Account) in.readObject()) !=null)
{
if (acc instanceof Account)
((Account)acc).print();
//acc.print();
}
}
catch(EOFException ex)
{
System.out.println("End of file reached.");
}
catch(ClassNotFoundException ex)
{
System.out.println("Error casting");
ex.printStackTrace();
}
catch(FileNotFoundException ex)
{
System.out.println("Error specified file does not exist");
ex.printStackTrace();
}
catch(IOException ex)
{
System.out.println("Error with I/O processes");
ex.printStackTrace();
}
finally
{
try
{
in.close();
}
catch(IOException ex)
{
System.out.println("Another IOException during the closing");
ex.printStackTrace();
}
}
}
代碼寫入對象文件
Account ac=new Account(posoOfil,poso,ariLoga,aitiol,diafor);
ac.print();
try{
OutputStream file = new FileOutputStream("Accounts.txt");
OutputStream buffer = new BufferedOutputStream(file);
ObjectOutput output = new ObjectOutputStream(buffer);
try{
output.writeObject(ac);
output.flush();
System.out.println("Object written to file");
}
finally{
output.close();
}
}
catch
(FileNotFoundException ex) {System.out.println("Error with specified file") ;
ex.printStackTrace();}
catch(IOException ex){
System.out.println("Cannot perform output.");
}
}
和類賬戶
public class Account implements Serializable {
private int arithmKat;
// private Date date ;
private int posoOfil;
private int posoKat;
private String ariLoga ;
private String aitiol;
private boolean diafor=false;
public Account(int posoOfil, int posoKat,String ariLoga,String aitiol,boolean diafor){
arithmKat++;
this.posoOfil=posoOfil;
this.posoKat=posoKat;
this.ariLoga=ariLoga;
this.aitiol=aitiol;
this.diafor=diafor;
}
void print(){
System.out.println(arithmKat+" "+posoOfil+" "+posoKat+" "+diafor);}
}
請編輯您的問題以設置您的代碼的格式。目前無法讀取。 – 2013-02-23 09:32:52
請重新格式化您的代碼,以便它可以真正被人讀取。 – Henry 2013-02-23 09:32:57
這實際上花了很多努力。 >。> – Achrome 2013-02-23 09:36:50