본문 바로가기

Java SE/RandomAccessFile 09

RandomAccessFile 09

RMI 클라이언트에서 부서명 변경을 요청하면 RMI 서버는 RandomAccessFile 을 이용하여 해당 사원의 부서명을 변경하고 그 결과를 클라이언트에게 전달하여 화면에 변경내용을 출력한다.

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

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

  raf = new RandomAccessFile("emp.dat", "rw");
  // 사원의 정보를 저장한다
  raf.seek(0);
  insertRecord(1000, "홍길동", "인사과", "서울시 광진구 군자동", 3000000);
  insertRecord(1004, "김인철", "시스템지원", "경기도 의정부시", 4500000);
  insertRecord(1010, "최재철", "개발지원과", "서울시 상계동", 3080000);
  insertRecord(1024, "김시준", "게임개발부", "경기도 성남시", 5500000);
  raf.close();

  Emp emp = getEmpByID(1010);
  System.out.println("사번:"+emp.getEmpno());
  System.out.println("성명:"+emp.getName());
  System.out.println("부서:"+emp.getDept());
  System.out.println("주소:"+emp.getAddress());
  System.out.println("급여:"+emp.getSal());

 }

 public static void insertRecord(int no, String name, String dept, String addr, int sal) throws Exception {
  raf = new RandomAccessFile("emp.dat", "rw");
  insertEmpno(no);
  insertName(name);
  insertDept(dept);
  insertAddress(addr);
  insertSal(sal);
  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);
 }

 public static Emp getEmpByID(int no) throws Exception {
  raf = new RandomAccessFile("emp.dat", "r");
  long fp = 0;
  while(true) {
   raf.seek(fp);
   try{
    if(raf.readInt()==no) {
      Emp emp = new Emp(no, getName(), getDept(), getAddress(), getSal());
   raf.close();
      return emp;
    }
   }catch(EOFException eof){
      System.out.println("검색결과 없음");
      raf.close();
      break;
   }
   fp+= 76;  // 한개의 레코드는 76바이트로 구성되었기 때문에 .....
  }
  return null;
 }

 private static String getName()  throws Exception {
  byte[] name = new byte[8];
  raf.read(name, 0, name.length);
  return new String(name).trim();
 }

 private static  String getDept()  throws Exception {
  byte[] dept = new byte[10];
  raf.read(dept, 0, dept.length);
  return new String(dept).trim();
 }

 private static  String getAddress()  throws Exception {
  byte[] addr = new byte[50];
  raf.read(addr, 0, addr.length);
  return new String(addr).trim();
 }

 private static  int getSal()  throws Exception {
  return raf.readInt();
 }
 
 public static void updateDept(int no, String newDept) throws Exception {
  raf = new RandomAccessFile("emp.dat", "rw");
  long fp = 0;
  while(true) {
    raf.seek(fp);
    try{
   if(raf.readInt()==no) {
    raf.seek(raf.getFilePointer()+8);
    insertDept(newDept);
    raf.close();
    break;
   }
    }catch(EOFException eof) {
     System.out.println("수정할 레코드를 찾을 수 없습니다.");
     raf.close();
     return;
    }
    fp += 76;
  }
  raf.close();
 }
}


Emp.java

class Emp implements java.io.Serializable
{
 private int empno, sal;
 private String name, dept, address;

 Emp(int empno, String name, String dept, String address, int sal) {
  this.empno = empno;
  this.name = name;
  this.dept = dept;
  this.address = address;
  this.sal = sal;
 }

 public int getEmpno() {
  return empno;
 }

 public String getName(){
  return name;
 }

 public String getDept() {
  return dept;
 }

 public String getAddress() {
  return address;
 }

 public int getSal() {
  return sal;
 }
}



 서버측 원격인터페이스

import java.rmi.*;

public interface EmpServer extends Remote {

 public Emp getEmpByID(int empno) throws RemoteException;
 public void updateDept(int empno, String newDept) throws RemoteException;

}


RMI 서버 클래스

import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.RMISecurityManager;
import java.rmi.server.UnicastRemoteObject;
import java.io.*;

public class EmpServerImpl extends UnicastRemoteObject implements EmpServer {
 
 public EmpServerImpl() throws RemoteException {
    super();
 }
 
 public Emp getEmpByID(int empno) {
  Emp emp = null;
  try{
  emp = RandomFileTest09.getEmpByID(empno);
  }catch(Exception e){
   e.printStackTrace();
  }
    return emp;
 }

 public void updateDept(int no, String newDept)  {
  try{
  RandomFileTest09.updateDept(no, newDept);
  }catch(Exception e){
   e.printStackTrace();
  }
 }

 
 public static void main(String args[]) {
 
  try {

      EmpServerImpl obj = new EmpServerImpl();
 
      Naming.rebind("EmpServer", obj);
 
      System.out.println("EmpServer bound in registry");

  } catch (Exception e) {

      System.out.println("EmpImpl err: " + e.getMessage());

      e.printStackTrace();

  }
 }
}


RMI 클라이언트

import java.rmi.*;
import java.io.*;

public class EmpClient {

    public static void main(String[] args) {

        try {
   BufferedReader  br = new  BufferedReader(new InputStreamReader(System.in));
   System.out.print("검색하실 사원의 사번을 입력해 주세요 ");
   String empno = br.readLine();

            EmpServer obj = (EmpServer)Naming.lookup("rmi://localhost/EmpServer");

            Emp emp = obj.getEmpByID(Integer.parseInt(empno));

            System.out.println("------------검색 결과------------");
   System.out.println("사번: "+emp.getEmpno());
   System.out.println("이름: "+emp.getName());
   System.out.println("부서: "+emp.getDept());
   System.out.println("주소: "+emp.getAddress());
   System.out.println("급여: "+emp.getSal());
   System.out.println("==========================");
   System.out.print("수정 1(부서), 2(주소), 3(급여) ");

   String strField = br.readLine();

   if(strField.equals("1")) {
    System.out.println("새 부서명을 5자 이내로 입력해 주세요 ");
    String newDept = br.readLine();
    obj.updateDept(emp.getEmpno(), newDept);
    Emp e = obj.getEmpByID(emp.getEmpno());
    System.out.println("부서명을 '"+e.getDept()+"' 으로 변경했습니다.");
    System.out.println("----------------------------------------------------------------");
    System.out.println(e.getEmpno()+", "+e.getName()+", "+e.getDept()+", "+e.getAddress()+", "+e.getSal());
   }else if(strField.equals("2")) {
    System.out.println("새 주소를 25자 이내로 입력해 주세요 ");
    String newAddr = br.readLine();
   }else if(strField.equals("3")) {
    System.out.println("새 급여액을 입력해 주세요 ");
    String newSal = br.readLine();
   }

 } catch (Exception e) {

            System.out.println(e.getMessage());

            e.printStackTrace();

        }
    }
}