Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

Java에서 RandomAccessFile로 .txt 파일을 읽는 방법은 무엇입니까?

<시간/>

일반적으로 파일에 데이터를 읽거나 쓰는 동안 파일의 시작 부분부터 데이터를 읽거나 쓸 수만 있습니다. 임의의 위치에서 읽기/쓰기가 불가능합니다.

java.io.RandomAccessFile Java의 클래스를 사용하면 임의 액세스 파일에 데이터를 읽고 쓸 수 있습니다.

이것은 인덱스가 있는 큰 바이트 배열과 유사하게 작동하거나 getFilePointer()를 사용하여 이 포인터의 위치를 ​​얻을 수 있는 파일 포인터로 알려진 커서 방법을 찾고 seek() 방법을 사용하여 설정합니다.

이 클래스는 파일에 데이터를 읽고 쓰는 다양한 방법을 제공합니다. readLine() 이 클래스의 메소드는 파일에서 다음 줄을 읽어서 String 형태로 반환합니다.

readLine()을 사용하여 파일에서 데이터를 읽으려면 이 클래스의 메소드 -

  • 필요한 파일의 경로를 String 형식으로 전달하여 File 클래스를 인스턴스화합니다.

  • StringBuffer 클래스를 인스턴스화합니다.

  • 위에서 생성한 File 객체와 액세스 모드(r:read, rw:read/write 등)를 나타내는 String을 전달하여 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