Java.io.RandomAccessFile.readByte() 方法



描述

java.io.RandomAccessFile.readByte() 方法從該檔案中讀取一個帶符號的八位值。此方法從檔案讀取一個位元組,起始位置為當前檔案指標。

宣告

以下是java.io.RandomAccessFile.readByte() 方法的宣告。

public final byte readByte()

引數

返回值

此方法將此檔案的下一個位元組作為帶符號的八位位元組返回。

異常

  • IOException − 如果發生 I/O 錯誤。如果已到達檔案結尾,則不會丟擲。

  • EOFException − 如果此檔案已到達結尾

示例

以下示例顯示了java.io.RandomAccessFile.readByte() 方法的使用。

package com.tutorialspoint;

import java.io.*;

public class RandomAccessFileDemo {
   public static void main(String[] args) {
   
      try {
         // create a new RandomAccessFile with filename test
         RandomAccessFile raf = new RandomAccessFile("c:/test.txt", "rw");

         // write something in the file
         raf.writeUTF("Hello World");

         // set the file pointer at 0 position
         raf.seek(0);

         // read byte
         System.out.println("" + raf.readByte());

         // set the file pointer at 0 position
         raf.seek(0);

         // write 0 at the start
         raf.write(0);

         // read byte
         System.out.println("" + raf.readByte());
      } catch (IOException ex) {
         ex.printStackTrace();
      }
   }
}

假設我們有一個文字檔案c:/test.txt,其內容如下。此檔案將用作示例程式的輸入:

ABCDE  

讓我們編譯並執行上面的程式,這將產生以下結果:

0
11
java_io_randomaccessfile.htm
廣告