> Java > java지도 시간 > 본문

Java에서 BufferedReader를 사용하여 끝부터 시작까지 파일을 읽는 방법은 무엇입니까?

Mary-Kate Olsen
풀어 주다: 2024-10-24 10:26:29
원래의
125명이 탐색했습니다.

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

Java에서 BufferReader를 사용하여 파일을 처음부터 끝까지 읽기

문제:
읽어야 합니다. BufferedReader를 사용하여 파일을 끝에서 처음으로 역순으로 읽습니다.

해결책:
표준 BufferedReader 클래스는 파일을 역순으로 읽는 것을 지원하지 않습니다. 그러나 이를 달성하기 위해 RandomAccessFile 클래스를 활용할 수 있습니다. 이를 수행하는 방법에 대한 예는 다음과 같습니다.

<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>
로그인 후 복사

이 예에서는 RandomAccessFile을 사용하여 파일 끝에서 시작하고 각각에 대해 파일 포인터를 뒤로 조정하여 끝부터 파일을 읽습니다. 줄을 읽었습니다. 각 줄을 읽을 때 파일의 시작 부분에 도달할 때까지 파일에서 시작 위치가 조정되므로 파일을 역순으로 읽을 수 있습니다.

위 내용은 Java에서 BufferedReader를 사용하여 끝부터 시작까지 파일을 읽는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!