본문 바로가기

JAVA/Java2021-3

RandomAccessFile 클래스

RandomAccessFile 클래스

: 입출력 클래스 중 유일하게 파일에 대한 입력과 출력을 동시에 할 수 있는 클래스

 

package Basic_Grammar.chap6.ch12File클래스;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

public class RandomAccessFileTest {
    public static void main(String[] args) throws IOException {
        RandomAccessFile randomAccessFile=new RandomAccessFile("random.txt","rw");
        randomAccessFile.writeInt(100);
        System.out.println("파일 포인터 위치 :"+randomAccessFile.getFilePointer());
        randomAccessFile.writeDouble(3.14);
        System.out.println("파일 포인터 위치 :"+randomAccessFile.getFilePointer());
        randomAccessFile.writeUTF("안녕하세요");
        System.out.println("파일 포인터 위치 :"+randomAccessFile.getFilePointer());

        //읽기전에 맨 앞으로 pointer를 보내줘야한다.
        randomAccessFile.seek(0);
        int i=randomAccessFile.readInt();
        double d=randomAccessFile.readDouble();
        String str=randomAccessFile.readUTF();

        System.out.println(i);
        System.out.println(d);
        System.out.println(str);
    }
}