⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 updaterandom.java

📁 《A first book of java》by Gary J.Bronson 北大出版社
💻 JAVA
字号:
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 + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -