Java.io.RandomAccessFile.writeByte() 方法



描述

java.io.RandomAccessFile.writeByte(int v) 方法將一個位元組作為單位元組值寫入檔案。寫入從檔案指標的當前位置開始。

宣告

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

public final void writeByte(int v)

引數

v − 要寫入的位元組值。

返回值

此方法不返回值。

異常

IOException − 如果發生 I/O 錯誤。

示例

以下示例演示了java.io.RandomAccessFile.writeByte() 方法的用法。

package com.tutorialspoint;

import java.io.*;

public class RandomAccessFileDemo {
   public static void main(String[] args) {

      try {
         byte[] b1 = {15, 8};
         
         // create a new RandomAccessFile with filename test
         RandomAccessFile raf = new RandomAccessFile("c:/test.txt", "rw");

         // write something in the file
         raf.writeByte(b1[0]);

         // 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.writeByte(b1[1]);

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

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

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

ABCDE  

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

15
8
java_io_randomaccessfile.htm
廣告