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

📄 directaccessfile.java

📁 Java the UML Way 书中所有源码
💻 JAVA
字号:
/*
 * DirectAccessFile.java   E.L. 2001-08-16
 *
 */
import java.io.*;
class DirectAccessFile {
  public static void main(String[] args) {

    try {
      RandomAccessFile file = new RandomAccessFile("DirectFile.dat", "rw");

      /* writes 10 integers to the file */
      for (int i = 0; i < 10; i++) file.writeInt(i);
      long fileLength = file.length();
      System.out.println("The file is " + fileLength + " bytes long.");

      /*
       * moves the file pointer to integer no. 7, reads i,
       * multiplies it by 10, and rewrites it to the file.
       */

      file.seek(6 * 4); // moves past 6 integers, each 4 bytes
      int number = file.readInt();
      number *= 10;
      file.seek(6 * 4); // moves the filepointer "back"
      file.writeInt(number);

      /* reads the whole file */
      file.seek(0);  // moves to the beginning of the file
      try {
        while (true) {  // stops when EOFException is thrown
          int t = file.readInt();
          System.out.println(t);
        }
      }
      catch (EOFException e) {
      }
      file.close();
    } catch (Exception e) {
      System.out.println("Error: " + e);
    }
  }
}

/* Example Run:
The file is 40 bytes long.
0
1
2
3
4
5
60
7
8
9
*/

⌨️ 快捷键说明

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