1

다음은 HashMap을 읽고 쓰는 데 사용하는 코드입니다. 어쨌든이 코드를 다시 고려하여 모든 데이터 구조를 읽고 쓸 수 있는지 궁금합니다. 각 데이터 구조에 대해 새로운 클래스를 만드는 것보다? 나는 어떤 도움을 주셔서 감사합니다!파일과의 데이터 구조 읽기 및 쓰기?

public static void writeOut(Serializable o, File selection) throws FileNotFoundException 

및 읽는데 (파일 선택)에서

public class FileHandler { 

    static ObjectOutputStream oos; 
    static ObjectInputStream ois; 


    public static void writeOut(HashMap p, File selection) throws FileNotFoundException, IOException 
     { 
     oos = new ObjectOutputStream(new FileOutputStream(selection)); 
     oos.writeObject(p); 
     oos.close(); 
     } 

     public static HashMap<String, Object> readIn(File selection) throws FileNotFoundException, IOException, ClassNotFoundException 
     { 
      HashMap<String, Object> temp = null; 
      ois = new ObjectInputStream(new FileInputStream(selection)); 
      temp = (HashMap<String, Object>) ois.readObject(); 
      ois.close(); 
     return temp; 
     } 


} 

답변

2

자민련은 (또한, 내가 try-with-resources을 사용)과 같은

public static void writeOut(Object p, File selection) 
     throws FileNotFoundException, IOException { 
    try (ObjectOutputStream oos = new ObjectOutputStream(
      new FileOutputStream(selection))) { 
     oos.writeObject(p); 
    } 
} 

public static Object readIn(File selection) throws FileNotFoundException, 
     IOException, ClassNotFoundException { 
    try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
      selection))) { 
     return ois.readObject(); 
    } 
} 
을 무언가를
2

변경 writeOut() 메소드 서명은, 당신은 체크되지 않은 작업을 수행하기 전에 몇 가지 instanceof 검사를 추가 할 수 있습니다 대신 HashMap<String, Object> temp

Object temp를 사용 readIn()을 사용할 때마다 유형 변환