본문 바로가기

Java SE/RandomAccessFile 05

RandomAccessFile 05


 

import java.io.*;
/* 레코드 검색을 위해 레코드를 구성하는 각 필드의 크기를 일정하게 제한하고 저장되는 데이터가
* 그 크기에 미치지 못하면 빈 자리를 강제로 채워서 필드의 크기를 맞춰준다
* 파일에 저장하는 코드를 메소드로 작성했다.
*/
class  RandomFileTest05
{
 static RandomAccessFile raf;
 static byte[] space;

 public static void main(String[] args) throws Exception
 {  // 사번(int) 사원이름(String, 8) 부서명(String, 10) 주소(String, 50) 급여(int)

  raf = new RandomAccessFile("emp.dat", "rw");

  space = new byte[64];  // 각 필드의 빈 공간을 채울 빈 바이트 배열

  // 사원의 정보를 저장한다
  insertRecord(1000, "홍길동", "인사과", "서울시 광진구 군자동", 3000000);
  insertRecord(1004, "김인철", "시스템지원", "경기도 의정부시", 4500000);
  insertRecord(1010, "최재철", "개발지원과", "서울시 상계동", 3080000);
  insertRecord(1024, "김시준", "게임개발부", "경기도 성남시", 2500000);
 
  // 홍길동의 주소만 가져와서 출력해 본다
  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();
 }

 public static void insertRecord(int no, String name, String dept, String addr, int sal) throws Exception {
  insertEmpno(no);
  insertName(name);
  insertDept(dept);
  insertAddress(addr);
  insertSal(sal);
 }

 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);
 }
}