Java.io.RandomAccessFile.writeFloat() 方法



描述

java.io.RandomAccessFile.writeFloat(float v) 方法將浮點型引數使用 Float 類中的 floatToIntBits 方法轉換為整數,然後將該整數值作為四個位元組的量寫入檔案,高位元組優先。寫入從檔案指標的當前位置開始。

宣告

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

public final void writeFloat(float v)

引數

v − 要寫入的浮點型值。

返回值

此方法不返回值。

異常

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

示例

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

package com.tutorialspoint;

import java.io.*;

public class RandomAccessFileDemo {
   public static void main(String[] args) {
   
      try {
         float f = 1847.4986f;

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

         // write a float in the file
         raf.writeFloat(f);

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

         // read float
         System.out.println("" + raf.readFloat());

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

         // write a float at the start
         raf.writeFloat(473.5645f);

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

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

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

ABCDE  

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

1847.4987
473.5645
java_io_randomaccessfile.htm
廣告

© . All rights reserved.