RandomAccessFile 을 이용하여 파일에 사원정보를 기록할 때 각 필드의 크기를 일정하게 제한하여 저장하면 검색이 쉽게 된다. 단점은 파일의 크기가 실제 데이터보다 더 커진다는 것이다.
import java.io.*;
/* 레코드 검색을 위해 레코드를 구성하는 각 필드의 크기를 일정하게 제한하고 저장되는 데이터가
* 그 크기에 미치지 못하면 빈 자리를 강제로 채워서 필드의 크기를 맞춰준다
*/
class RandomFileTest03
{
public static void main(String[] args) throws Exception
{
RandomAccessFile raf = new RandomAccessFile("emp.dat", "rw");
// 사번(int) 사원이름(String) 부서명(String) 주소(String) 급여(int)
byte[] space = new byte[64]; // 각 필드의 빈 공간을 채울 빈 바이트 배열
raf.writeInt(1000); // 사번: 4바이트로 제한함
byte[] name = "홍길동".getBytes();
raf.write(name); // 8바이트
raf.write(space, 0, 8-name.length); // 3자이름은 6바이트이므로 비어있는 바이트 2개를 써서 자리를 채운다
byte[] dept = "총무과".getBytes();
raf.write(dept); // 10바이트
raf.write(space, 0, 10-dept.length);
byte[] address = "서울시 광진구 군자동".getBytes();
raf.write(address); // 50바이트
raf.write(space, 0, 50-address.length);
raf.writeInt(200000); // 4바이트
// 홍길동의 주소만 가져와서 출력해 본다
raf.seek(22);
byte[] buf = new byte[64];
raf.read(buf, 0, 50);
String addr = new String(buf, 0, 50);
addr = addr.trim();
System.out.println(addr);
}
}