Java에서 역순으로 파일을 읽는 방법은 무엇입니까?
Java에서 파일을 역순으로 읽기
문제:
파일을 마지막 줄부터 역순으로 읽어야 하고
해결책:
Random Access File and Line Scanning
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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











2025 년 상위 4 개의 JavaScript 프레임 워크 : React, Angular, Vue, Svelte

카페인 또는 구아바 캐시와 같은 라이브러리를 사용하여 자바 애플리케이션에서 다단계 캐싱을 구현하려면 어떻게해야합니까?

Java의 클래스로드 메커니즘은 다른 클래스 로더 및 대표 모델을 포함하여 어떻게 작동합니까?

Spring Boot Snakeyaml 2.0 CVE-2022-1471 문제 고정

캐싱 및 게으른 하중과 같은 고급 기능을 사용하여 객체 관계 매핑에 JPA (Java Persistence API)를 어떻게 사용하려면 어떻게해야합니까?

고급 Java 프로젝트 관리, 구축 자동화 및 종속성 해상도에 Maven 또는 Gradle을 어떻게 사용합니까?
