updaterandom.java

来自「《A first book of java》by Gary J.Bronson 」· Java 代码 · 共 64 行

JAVA
64
字号
import java.io.*;
public class UpdateRandom
{
 
  static final int RECLEN = 16;    // record length in bytes
  static final int BASEREC = 1000;

  public static void main(String[] args)
    throws java.io.IOException
  {
    String fileName = "products.dat";
    String acctstring, amtstring, pricestring;
    int acct, amt;
    int recnum;
    double price;
    long filelen, position, setbytepos;

      // set up the keyboard for string input
    InputStreamReader isr = 
	new InputStreamReader(System.in);
    BufferedReader br = 
	new BufferedReader(isr);

      // set up the basic random access input/output stream
    RandomAccessFile raf = 
        new RandomAccessFile(fileName, "rw");

    filelen = raf.length();  // get length of the file
    System.out.print("Enter the identification number (999 to stop): ");
    acctstring = br.readLine();

    while (!acctstring.equals("999"))
    {
        // calculate the record number for this id number
      recnum = Integer.parseInt(acctstring) - BASEREC;  
        // calculate the startingbyte position for this record 
      position = (recnum - 1) * RECLEN;  
        // make sure this is a valid byte position
      if (position < 0 || position > (filelen - 1))
      {
        System.out.println("There is no record for this id number");
        System.out.print("Please recheck and reenter the identification "
                        + "number (999 to stop): ");
        acctstring = br.readLine();     
        continue;
      }
      raf.seek(position);  // move to the record
      acct = raf.readInt();
      setbytepos = raf.getFilePointer();
      amt = raf.readInt();
      System.out.println("The current quantity in stock is: " + amt);
      System.out.print("Enter the new quantity: ");
      amtstring = br.readLine();
      amt = Integer.parseInt(amtstring);
      raf.seek(setbytepos);  // reset position to the amt field
      raf.writeInt(amt);      
      System.out.println("The record has been updated.");
      System.out.print("Enter a new identification number (999 to stop): ");
      acctstring = br.readLine();
    }
    
    raf.close();
  }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?