Java SE/RandomAccessFile 01

RandomAccessFile 01

Soul-Learner 2008. 4. 21. 11:55


 

import java.io.*;

class  RandomFileTest01
{
 public static void main(String[] args) throws Exception
 {
  RandomAccessFile raf = new RandomAccessFile("emp.dat", "rw");
  // 사번(int) 사원이름(String) 부서명(String) 주소(String) 급여(int)
  raf.writeInt(1000);
  raf.write("홍길동".getBytes());
  raf.write("총무과".getBytes());
  raf.write("서울시 광진구 군자동".getBytes());
  raf.writeInt(200000);

  // 홍길동의 주소를 출력해 본다.
  raf.seek(16);  // 파일포인터를 주소필드 앞에 위치한다
  byte[] buf = new byte[64];  // 주소를 읽어와서 저장할 공간을 준비한다
  raf.read(buf, 0, 20);  // 주소가 차지하는 공간이 총 20바이트이므로 현재 위치에서 20바이트를 읽어온다
  String address = new String(buf, 0, 20); // 바이트를 문자열로 변환한다

  System.out.println(address);
 }
}