Javaでファイルを逆の順序で読み取るにはどうすればよいですか?

Patricia Arquette
リリース: 2024-10-25 06:10:29
オリジナル
232 人が閲覧しました

How to Read a File in Reverse Order in Java?

Java でファイルを逆の順序で読み取る

問題:

ファイルを最後の行から始めて逆の順序で読み取る必要があります。

解決策:

ランダム アクセス ファイルとライン スキャンの使用

BufferedReader を使用してファイルを逆順に読み取るには、次のことができます。 RandomAccessFile を利用してファイル ポインタを操作し、逆の順序で改行をスキャンします。

Java でこのアプローチを実装する方法は次のとおりです:

<code class="java">import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;

public class ReverseFileReader {

    public static void readAndReverse(String filePath) {
        try {
            // Create a RandomAccessFile instance for the file
            RandomAccessFile file = new RandomAccessFile(filePath, "r");

            // Calculate the file length
            long fileLength = file.length();

            // Create an ArrayList to store the lines of the file
            ArrayList<String> lines = new ArrayList<>();

            // Set the file pointer to the end of the file
            file.seek(fileLength);

            // Scan backwards line by line, starting from the last line
            while (file.getFilePointer() > 0) {
                // Find the previous line break and move the file pointer to that position
                long lineStart = file.getFilePointer();
                while (file.getFilePointer() > 0 && file.readByte() != '\n') {
                    file.seek(file.getFilePointer() - 1);
                }

                // Read the line and add it to the list
                file.seek(lineStart);
                lines.add(file.readLine());
            }

            // Close the file
            file.close();

            // Reverse the order of the lines in the list
            Collections.reverse(lines);

            // Print the lines in reverse order
            for (String line : lines) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        // Specify the file path to be read in reverse order
        String filePath = "/path/to/your/file.txt";

        // Read and reverse the file
        readAndReverse(filePath);
    }
}</code>
ログイン後にコピー

実装の詳細:

  • RandomAccessFile を使用してファイル ポインタを動的に移動し、ファイルを逆の順序でスキャンします。
  • 行を ArrayList に保存して元の順序を保持し、印刷する前にリストを逆にします。
  • readLine() メソッドは、ファイル ポインターの位置から行を逆に読み取るために使用されます。
  • 逆の順序で改行をスキャンすることで、ファイルを最後から最初まで効果的に読み取ります。

以上がJavaでファイルを逆の順序で読み取るにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:php
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
著者別の最新記事
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!