Java.io.RandomAccessFile.write() 方法



描述

java.io.RandomAccessFile.write(byte[] b,int off,int len) 方法將從指定位元組陣列中從偏移量 off 開始的 len 個位元組寫入到此檔案中。

宣告

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

public void write(byte[] b,int off,int len)

引數

  • b − 資料。

  • off − 資料中的起始偏移量。

  • len − 要寫入的位元組數。

返回值

此方法不返回值。

異常

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

示例

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

package com.tutorialspoint;

import java.io.*;

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

      try {
         byte[] b = {1, 2, 3, 4, 5, 6};
         
         // create a new RandomAccessFile with filename test
         RandomAccessFile raf = new RandomAccessFile("c:/test.txt", "rw");

         // write 2 bytes in the file
         raf.write(b, 2, 2);

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

         // print the two bytes we wrote
         System.out.println("" + raf.readByte());
         System.out.println("" + raf.readByte());
         
      } catch (IOException ex) {
         ex.printStackTrace();
      }
   }
}

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

ABCDE  

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

3
4
java_io_randomaccessfile.htm
廣告