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
广告

© . All rights reserved.