首頁  >  文章  >  Java  >  Java中如何使用BufferedReader從頭到尾讀取檔案?

Java中如何使用BufferedReader從頭到尾讀取檔案?

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-10-24 10:26:29117瀏覽

How to Read a File from End to Start Using BufferedReader in Java?

在Java 中使用BufferReader 從頭到尾讀取檔案

問題:

問題:

問題:
<code class="java">import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.RandomAccessFile;

public class ReverseFileReader {

    public static void main(String[] args) {
        // Create a RandomAccessFile to access the file
        RandomAccessFile file = null;
        BufferedReader reader = null;
        try {
            file = new RandomAccessFile("filepath.txt", "r");

            // Get the file size
            long fileSize = file.length();

            // Start reading from the end of the file
            file.seek(fileSize - 1);

            // Initialize a BufferedReader to read from the RandomAccessFile
            reader = new BufferedReader(new FileReader(file.getFD()));

            // Read the file line by line in reverse order
            while ((file.getFilePointer()) > 0) {
                // Get the current line
                String line = reader.readLine();

                // Adjust the file pointer to the beginning of the previous line
                file.seek(file.getFilePointer() - line.length() - 1);

                // Print the line
                System.out.println(line);
            }
        } catch (FileNotFoundException e) {
            System.out.println("File not found.");
        } catch (IOException e) {
            System.out.println("Error reading file.");
        } finally {
            // Close the file and the reader
            try {
                if (file != null) file.close();
                if (reader != null) reader.close();
            } catch (IOException e) {}
        }
    }
}</code>

問題:問題:問題:問題:問題:您需要閱讀使用BufferedReader 從末尾到開頭以相反的順序讀取文件。 解決方案:標準 BufferedReader 類別不支援以相反順序讀取檔案。但是,您可以利用 RandomAccessFile 類別來實現此目的。以下是如何執行此操作的範例:在此範例中,RandomAccessFile 用於從文件末尾開始讀取文件,並向後調整每個文件的文件指標行讀取。讀取每一行時,會調整其在檔案中的起始位置,直到到達檔案開頭,讓您以相反的順序讀取檔案。

以上是Java中如何使用BufferedReader從頭到尾讀取檔案?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn