Java.io.RandomAccessFile.readLine() 方法



描述

java.io.RandomAccessFile.readLine() 方法從該檔案中讀取下一行文字。此方法從檔案中的當前檔案指標開始,依次讀取位元組,直到到達行終止符或檔案結尾。每個位元組都透過取位元組值的低八位作為字元的低八位,並將字元的高八位設定為零來轉換為字元。

宣告

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

public final String readLine()

引數

返回值

此方法返回該檔案中的下一行文字,如果在讀取任何位元組之前遇到檔案結尾,則返回 null。

異常

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

示例

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

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);

         // print the line
         System.out.println("" + raf.readLine());

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

         // write something in the file
         raf.writeUTF("This is an example \n Hello World");

         raf.seek(0);
         // print the line
         System.out.println("" + raf.readLine());
         
      } catch (IOException ex) {
         ex.printStackTrace();
      }
   }
}

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

ABCDE  

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

Hello World
This is an example
java_io_randomaccessfile.htm
廣告