Java.io.RandomAccessFile.close() 方法



描述

java.io.RandomAccessFile.close() 方法關閉此隨機訪問檔案流並釋放與該流關聯的任何系統資源。已關閉的隨機訪問檔案無法執行輸入或輸出操作,也無法重新開啟。

宣告

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

public void close()

引數

返回值

此方法不返回值。

異常

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

示例

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

package com.tutorialspoint;

import java.io.*;

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

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

         // write something in the file
         raf.writeUTF("Hello World");

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

         // read and print the contents of the file
         System.out.println("" + raf.readUTF());

         // close the strea and release resources
         System.out.println("Closing Stream...");
         raf.close();
         System.out.println("Stream Closed.");
      } catch (IOException ex) {
         ex.printStackTrace();
      }
   }
}

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

ABCDE  

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

Hello World
Closing Stream...
Stream Closed.
java_io_randomaccessfile.htm
廣告