여러 개체가있는 파일을 직렬화했습니다. 그래서 아래와 같은 코드를 작성했습니다.
FileOutputStream outputStream=new FileOutputStream(new File("Output.ser"));
ObjectOutputStream objectOutputStream=new ObjectOutputStream(outputStream);
objectOutputStream.writeObject(employee);
objectOutputStream.writeObject(employee2);
objectOutputStream.writeObject(employee3);
objectOutputStream.writeObject(employee4);
objectOutputStream.close();
이제 나는 그것을 역 직렬화하고 싶기 때문에 모든 객체를 반복하기 위해 WHILE 루프의 도움을 받았습니다! 코드는 다음과 같습니다.
FileInputStream fileInputStream=new FileInputStream(new File(fileName));
ObjectInputStream stream=new ObjectInputStream(fileInputStream);
Employee emp;
while((emp=(Employee) stream.readObject())!=null)
{
String uName=emp.getUserId();
String uPass=emp.getPassword();
map.put(uName, uPass);
}
이 코드는 파일 끝에 도달하는 EOFException을 생성합니다. readObject ()가 파일 끝에 도달하면 null을 반환해야한다고 생각하지만이 경우에는 예외가 발생했습니다! 예외없이 직렬화 된 파일을 성공적으로 읽을 수있는 방법을 제안 해주세요!
여러 객체를 직렬화하는 대신 다음 List
과 같이 직렬화해야합니다 .
FileOutputStream outputStream=new FileOutputStream(new File("Output.ser"));
ObjectOutputStream objectOutputStream=new ObjectOutputStream(outputStream);
ArrayList<Employee> employees = new ArrayList<Employee>();
employees.add(employee);
employees.add(employee2);
employees.add(employee3);
employees.add(employee4);
objectOutputStream.writeObject(employees);
objectOutputStream.close();
다음과 같이 역 직렬화 할 수 있습니다.
FileInputStream fileInputStream=new FileInputStream(new File(fileName));
ObjectInputStream stream=new ObjectInputStream(fileInputStream);
for(Employee emp : (ArrayList)stream.readObject())
{
String uName = emp.getUserId();
String uPass = emp.getPassword();
map.put(uName, uPass);
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다