Java.io.RandomAccessFile.writeUTF() 方法



描述

java.io.RandomAccessFile.writeUTF(String str) 方法以機器無關的方式使用修改後的 UTF-8 編碼將字串寫入檔案。

宣告

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

public final void writeUTF(String str)

引數

str - 要寫入的字串。

返回值

此方法不返回值。

異常

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

示例

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

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 string in the file
         raf.writeUTF(s);

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

         // read string
         System.out.println("" + raf.readUTF());

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

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

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

         // read string
         System.out.println("" + raf.readUTF());
         
      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }
}

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

ABCDE  

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

Hello world
This is an example
java_io_randomaccessfile.htm
廣告

© . All rights reserved.