Java HashMap 파일 입출력 (File IO)

image_pdfimage_print

[펌] https://m.blog.naver.com/PostView.naver?isHttpsRedirect=true&blogId=lsj30224&logNo=220586099250

HashMap파일 입출력방법

출력 :

주의!!!    자료형처럼 쓰는 클래스는 Serializable 을 구현해야함

    public static void main(String[] args) {
        HashMap<String, Data> hm = new HashMap<String, Data>();
        
        hm.put("Key1", new Data(1, "Key1 String Value", true)); 
        
        try {
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("출력할 파일 이름"));
            oos.writeObject(hm);
            oos.close();
        } catch (IOException ex) {
            Logger.getLogger(Tester.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }

입력 (위에서 출력한 파일 받아옴)

받아올때는 자료형 변환 해줘야 합니다.

(이것도 좀 기네요 오른쪽으로 스크롤 해주세요)

    public static void main(String[] args) {
        HashMap<String, Data> hm = new HashMap<String, Data>();
        
        try {
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream("출력할 파일 이름"));
            hm = (HashMap<String, Data>) ois.readObject();   //캐스팅 해줘야됨
        } catch (IOException ex) {
            Logger.getLogger(Tester.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Tester.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        System.out.println("intval : "+hm.get("Key1").intval+", strval : "+hm.get("Key1").strval+", boolval : "+hm.get("Key1").boolval);
    }
 

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다