import java.io.*;
/* 레코드 검색을 위해 레코드를 구성하는 각 필드의 크기를 일정하게 제한하고 저장되는 데이터가
* 그 크기에 미치지 못하면 빈 자리를 강제로 채워서 필드의 크기를 맞춰준다
* 파일에 저장하는 코드를 메소드로 작성했다.
*/
class RandomFileTest04
{
static RandomAccessFile raf;
static byte[] space;
public static void main(String[] args) throws Exception
{ // 사번(int) 사원이름(String) 부서명(String) 주소(String) 급여(int)
raf = new RandomAccessFile("emp.dat", "rw");
space = new byte[64]; // 각 필드의 빈 공간을 채울 빈 바이트 배열
// 한 사원의 정보를 저장한다
insertEmpno(1000); // 4
insertName("홍길동"); // 8
insertDept("인사과"); // 10
insertAddress("서울시 광진구 군자동"); // 50
insertSal(3000000); // 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);
raf.close();
}
private static void insertEmpno(int empno) throws Exception {
raf.seek(raf.length());
raf.writeInt(empno);
}
private static void insertName(String empName) throws Exception {
byte[] name = empName.getBytes();
raf.write(name); // 8바이트
raf.write(space, 0, 8-name.length);
}
private static void insertDept(String department) throws Exception {
byte[] dept = department.getBytes();
raf.write(dept); // 10바이트
raf.write(space, 0, 10-dept.length);
}
private static void insertAddress(String addr) throws Exception {
byte[] address = addr.getBytes();
raf.write(address); // 50바이트
raf.write(space, 0, 50-address.length);
}
private static void insertSal(int sal) throws Exception {
raf.writeInt(sal);
}
}