Java
 Computer >> コンピューター >  >> プログラミング >> Java

JavaでRandomAccessFileを使用して.txtファイルを読み取る方法は?


一般に、ファイルの読み取りまたは書き込み中は、ファイルの先頭からのみデータの読み取りまたは書き込みを行うことができます。ランダムな位置からの読み取り/書き込みはできません。

java.io. RandomAccessFile Javaのクラスを使用すると、ランダムアクセスファイルへのデータの読み取り/書き込みが可能になります。

これは、インデックスまたはファイルポインタと呼ばれるカーソルを持つバイトの大きな配列と同様に機能し、 getFilePointer()を使用してこのポインタの位置を取得できます。 メソッドを作成し、seek()メソッドを使用して設定します。

このクラスは、データをファイルに読み書きするためのさまざまなメソッドを提供します。 readLine() このクラスのメソッドは、ファイルから次の行を読み取り、Stringとして形式で返します。

readLine()を使用してファイルからデータを読み取るには このクラスのメソッド-

  • 必要なファイルのパスを文字列形式で渡して、Fileクラスをインスタンス化します。

  • StringBufferクラスをインスタンス化します。

  • 上記で作成したFileオブジェクトとアクセスモード(r:read、rw:read / writeなど)を表す文字列を渡すことにより、RandomAccessFileクラスをインスタンス化します。

  • ファイルの位置が長さよりも小さい間、ファイルを反復処理します(length()メソッド)。

  • 上で作成したStringBufferオブジェクトに各行を追加します。

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessFileExample {
   public static void main(String args[]) throws IOException {
      String filePath = "D://input.txt";
      //Instantiating the File class
      File file = new File(filePath);
      //Instantiating the StringBuffer
      StringBuffer buffer = new StringBuffer();
      //instantiating the RandomAccessFile
      RandomAccessFile raFile = new RandomAccessFile(file, "rw");
      //Reading each line using the readLine() method
      while(raFile.getFilePointer() < raFile.length()) {
         buffer.append(raFile.readLine()+System.lineSeparator());
      }
      String contents = buffer.toString();
      System.out.println("Contents of the file: \n"+contents);
   }
}

出力

Contents of the file:
Tutorials Point originated from the idea that there exists a class of readers who respond better 
to online content and prefer to learn new skills.
Our content and resources are freely available and we prefer to keep it that way to encourage 
our readers acquire as many skills as they would like to.
We don’t force our readers to sign up with us or submit their details either.
Enjoy the free content

  1. JavaでCSVファイルからデータを読み取る方法は?

    CSV カンマ区切り値の略です 。 CSVファイルでは、各行にカンマ(、)で区切られた単語が含まれています そしてそれは 。csvとともに保存されます 拡張機能。 readLine()を使用して、CSVファイルを1行ずつ読み取ることができます BufferedReaderのメソッド クラス。各行をコンマ文字で分割して、その行の単語を配列に入れます。これで、配列を反復処理するか、適切なインデックスを使用して、配列の内容を簡単に印刷できます。 CSVファイル 例 import java.io.*; public class CSVReaderTest {    p

  2. Javaのプロパティファイルからデータを読み取る方法は?

    プロパティ はHashtableクラスのサブクラスであり、プロパティの永続的なセットを表します。 プロパティ ストリームに保存することも、ストリームからロードすることもできます。プロパティリストの各キーとそれに対応する値は文字列です。 プロパティ ファイルをJavaで使用して、構成を外部化し、キーと値のペアを保存できます。 。 Properties.load()メソッド ofPropertiesクラスはロードに便利です。プロパティ key-valueの形式のファイル ペア 。 構文 public class Properties extends Hashtable credential