JAVA/포스팅

자바 RandomAccessFile

짜집퍼박사(짜박) 2023. 11. 26. 20:29

RandomAccessFile 클래스는 파일에 대한 읽기 및 쓰기 작업을 지원하는 클래스로, 파일 내의 임의의 위치에서 데이터를 읽거나 쓸 수 있습니다. 이 클래스는 입출력 스트림과 유사하지만, 파일에 대한 임의 접근(랜덤 액세스)을 제공하는 점에서 다릅니다.

 

1. RandomAccessFile 클래스의 생성자

RandomAccessFile 클래스는 다음과 같은 두 가지 생성자를 제공합니다.

 

- RandomAccessFile(File file, String mode) : 파일 객체와 모드를 인자로 받아 객체를 생성합니다. 모드는 "r" (읽기), "rw" (읽기 및 쓰기), "rws" (동기적으로 파일 내용 및 메타데이터 갱신) 등이 있습니다.

- RandomAccessFile(String name, String mode): 파일 경로와 모드를 인자로 받아 객체를 생성합니다.

 

2. RandomAccessFile의 주요 메서드

- read() 및 readFully(byte[] b, int off, int len): 파일에서 데이터를 읽습니다.

RandomAccessFile file = new RandomAccessFile("example.txt", "r");
int data = file.read(); // 한 바이트 읽기
byte[] buffer = new byte[10];
file.readFully(buffer, 0, 10); // 10바이트 읽기

- write(int b) 및 write(byte[] b, int off, int len): 파일에 데이터를 씁니다.

RandomAccessFile file = new RandomAccessFile("example.txt", "rw");
file.write(65); // ASCII 코드 65는 'A'
byte[] data = "Hello".getBytes();
file.write(data, 0, data.length);

- seek(long pos): 파일 포인터를 지정한 위치로 이동시킵니다.

RandomAccessFile file = new RandomAccessFile("example.txt", "r");
file.seek(10); // 파일 포인터를 10번째 바이트로 이동

- length(): 파일의 길이를 반환합니다.

RandomAccessFile file = new RandomAccessFile("example.txt", "r");
long length = file.length(); // 파일의 전체 길이

- close(): 파일을 닫습니다.

RandomAccessFile file = new RandomAccessFile("example.txt", "r");
// 파일 작업 수행
file.close(); // 파일 닫기

 

다음은 RandomAccessFile을 사용하여 파일에 데이터를 쓰고 읽는 간단한 예제입니다.

import java.io.*;

public class RandomAccessFileExample {
    public static void main(String[] args) {
        try {
            // 파일에 데이터 쓰기
            RandomAccessFile writeFile = new RandomAccessFile("example.txt", "rw");
            writeFile.writeUTF("Hello, RandomAccessFile!");
            writeFile.close();

            // 파일에서 데이터 읽기
            RandomAccessFile readFile = new RandomAccessFile("example.txt", "r");
            String data = readFile.readUTF();
            System.out.println("Read from file: " + data);
            readFile.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

이 예제에서는 writeUTF() 메서드로 문자열을 파일에 쓰고, readUTF() 메서드로 파일에서 문자열을 읽어오고 있습니다.

 

With ChatGPT

'JAVA > 포스팅' 카테고리의 다른 글

자바 직렬화(Serialization)  (0) 2023.11.26
자바 File  (0) 2023.11.26
자바 표준입출력 setIn()  (0) 2023.11.26
자바 표준입출력 setErr()  (0) 2023.11.26
자바 표준입출력 setOut()  (0) 2023.11.26