我有一个大问题,我在一个txt文件中写相同的对象帐户当我点击查看我在txt中写的所有对象时只显示我的最后一个以及我如何在JOptionPane中显示该帐户,第二个是我怎么能让帐户拿nuber一,二,三......我写的每个帐户从先例帐户中取一个加号。 我相信解释明显的
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);}
}
答案 0 :(得分:0)
您只能将一个帐户写入该文件。编写帐户的代码中根本没有循环。写几个帐户的代码如下所示:
private void writeAccounts(List<Account> accounts) throws IOException {
OutputStream file = new FileOutputStream("Accounts.txt");
OutputStream buffer = new BufferedOutputStream(file);
ObjectOutput output = new ObjectOutputStream(buffer);
try {
for (Account account : accounts) {
output.writeObject(account);
}
output.close();
}
finally {
output.close();
}
}