txt文件中的数据被覆盖

时间:2013-08-06 00:42:43

标签: java randomaccessfile

该程序应该为.txt文件创建一些空白记录,稍后可以编辑该文件以添加名称和余额等信息。我的问题是每当我放入另一条记录时,第一个帐户的余额消失(但名称没有)。如果我尝试添加另一个帐户,前一个帐户的余额也会消失。它可能被覆盖了什么。

我该如何解决这个问题?

import java.io.*;

public class CreateBankFile {
   private RandomAccessFile file;

   public static void main(String[] args) throws IOException {
      CreateBankFile blank = new CreateBankFile();
   }

   public CreateBankFile() throws IOException{
      initialize();
      int task = 0;
      while(task == 0)
      {
         writeRecord();
      }
   }

   private void initialize() {
      Account acc = new Account();

      try {
         File fileName = new File("C:/Documents and Settings/x/Desktop/hehe.txt");
         file = new RandomAccessFile( fileName, "rw" );

         // Create 100000 blank records in the file
         for ( int i = 0; i < 100001; i++)
            acc.write( file );
      } catch ( IOException ioex ){
         System.out.println("File does not exists");
      }
   }

    private void writeRecord() throws IOException {
       Account acc = new Account();
       BufferedReader data = new BufferedReader(new InputStreamReader(System.in));
       System.out.println("Enter Account # ");
       String accNo = data.readLine();
       int recordNumber = Integer.parseInt(accNo);

       try {

          File fileName = new File("C:/Documents and Settings/x/Desktop/hehe.txt");
          file = new RandomAccessFile( fileName, "rw" );

          // Write the record to the file
          if ( recordNumber > 0 && recordNumber < 100001 ) {

             System.out.println("Enter Account Name: ");
             String neym = data.readLine();
             System.out.println("Enter Remaining Balance: ");
             String numbah = data.readLine();
             acc.setName(neym);
             acc.setBalance(numbah);

             // Go to the record location
             file.seek( (recordNumber - 1) * acc.size() );

             // Write the record out
             acc.write( file );

             System.out.println("\nUpdate Succesful!\n");
             System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
          }
       } catch ( Exception ioex ){
          System.out.println("File does not exists");
       }
   }
}


class Account {
   private String name;
   private String balance;

   // Constructor
   public Account() { this ("", ""); }

   // Overloaded Constructor
   public Account(String n, String b) {
      name = n;
      balance = b;
   }

   // Public method to read the data from the file
   public void read( RandomAccessFile file ) throws IOException {
      setName( padData( file ) );
      setBalance ( padData( file ) );
   }

   // Public method to write the data to the file
   public void write( RandomAccessFile file ) throws IOException {
      writeData( file, getName() );
      writeData( file, getBalance() );
   }

   // The method that actually writes the data to the file

   private void writeData(RandomAccessFile f, String n) throws IOException {
      StringBuffer buf = null;

      if ( n != null )
         buf = new StringBuffer( n );
      else
         buf = new StringBuffer( 20 );
         buf.setLength( 20 );
         f.writeChars( buf.toString() );
   }

   // This pads the data so to make the data all the same size
   // we will go for a size of 20
   private String padData( RandomAccessFile f ) throws IOException {
      char data[] = new char[ 20 ], temp;

      for ( int i = 0; i < data.length; i++ ) {
         temp = f.readChar();
         data[ i ] = temp;
      }

      return new String ( data ).replace( '\0', ' ' );
   }

   // This method hard codes the value for the size of the record
   // which is 20
   public static int size() { return 20; }

   // The get and set methods
   public void setName(String n) { name = n; }

   public void setBalance(String b) { balance = b; }

   public String getName() { return name; }

   public String getBalance() { return balance; }
}

3 个答案:

答案 0 :(得分:1)

除了其他人指出的任何其他问题。

   buf.setLength( 20 );
你只写了20个字符。您还需要在if语句中使用大括号:

private void writeData(RandomAccessFile f, String n) throws IOException {
  StringBuffer buf = null;

  if ( n != null )
     buf = new StringBuffer( n );
  else {
     buf = new StringBuffer( 20 );
     buf.setLength( 20 );
  }

  f.writeChars( buf.toString() );
}

答案 1 :(得分:0)

问题在于:

// Create 100000 blank records in the file
for ( int i = 0; i < 100001; i++)
    acc.write( file );

您的initialize()函数中有这个函数,CreateBankFile()中调用了main()中调用的{{1}}

因此,每次运行程序时,都会重新初始化文件。歼灭。因此,删除该代码,您的程序应该工作。

(虽然您必须在第一次初始化文件时,可能会创建第二个程序来初始化文件或将其作为用户选项,或检测文件是否存在并初始化它,如果它尚未存在。)

答案 2 :(得分:0)

我绝对不是专家,但我确实在您的代码中看到了一些错误。在此行中,您将文件指针设置为指向所需的记录:

// Go to the record location
file.seek( (recordNumber - 1) * acc.size() );

但是,在您的帐户类中,您将字段大小设置为20:

public static int size() { return 20; }

仔细看看java API会发现你在这里使用的writeChars方法 -

 private void writeData(RandomAccessFile f, String n) throws IOException {
  StringBuffer buf = null;

  if ( n != null )
     buf = new StringBuffer( n );
  else
     buf = new StringBuffer( 20 );
     buf.setLength( 20 );
     f.writeChars( buf.toString() );

}

被写为一系列字符,这些字符是重要的部分,每个字符都写成两字节值。现在,当您将指针设置为特定记录时,搜索值以字节为单位而不是以字符为单位。因此,当您打开文件并将指针设置为大于第一条记录的特定记录时,您将覆盖数据,因为字段的实际大小为40而不是20(记住字节,而不是字符)。希望我帮忙。