Java.io.RandomAccessFile.writeChars() 方法



描述

java.io.RandomAccessFile.writeChars(String s) 方法將字串作為一系列字元寫入檔案。每個字元都像 writeChar 方法一樣寫入資料輸出流。寫入從檔案指標的當前位置開始。

宣告

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

public final void writeChars(String s)

引數

s − 要寫入的字串值。

返回值

此方法不返回值。

異常

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

示例

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

package com.tutorialspoint;

import java.io.*;

public class RandomAccessFileDemo {
   public static void main(String[] args) {
   
      try {
         String s = "Hello World";

         // create a new RandomAccessFile with filename test
         RandomAccessFile raf = new RandomAccessFile("c:/test.txt", "rw");

         // write a char in the file
         raf.writeChars(s);

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

         // read chars
         for (int i = 0; i < 11; i++) {
            System.out.print("" + raf.readChar());
         }

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

         // change the line for better view
         System.out.println();

         // write a char at the start
         raf.writeChars("This is an example");

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

         // read chars
         for (int i = 0; i < 18; i++) {
            System.out.print("" + raf.readChar());
         }
         
      } catch (IOException ex) {
         ex.printStackTrace();
      }
   }
}

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

ABCDE  

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

Hello World
This is an example
java_io_randomaccessfile.htm
廣告

© . All rights reserved.