티스토리 뷰

JAVA

Serialization example code in java

seoca 2019. 7. 17. 07:04

 

 

Reading and Writing Java Object to a file in java

 

//Serialization 직렬화 - Object 자체를 file 에 저장하고 싶을 때 사용. 이 클래스를 상속하는 하위클래스들도 직렬화가 가능해진다.
public class PhoneInfo implements Serializable {
...
}
 

 

public class PhoneManager {
 
private final File dataFile = new File("PhoneBook.txt"); //create file
 
...
 
    public void storeFile(){
        FileOutputStream file = null;
        try {
            file = new FileOutputStream(dataFile);
            try {
                ObjectOutputStream out = new ObjectOutputStream(file); //converted into byte-stream
                Iterator<PhoneInfo> itr = phoneInfo.iterator();
                while(itr.hasNext())
                    out.writeObject(itr.next());
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
 
 
public void readFile() throws ClassNotFoundException {
    if (!dataFile.exists())
        return;
 
    ObjectInputStream in = null;
    try {
        FileInputStream fileIn = new FileInputStream(dataFile);
        if (fileIn == null) {
            throw new IOException("Can't find file.");
        }
        in = new ObjectInputStream(fileIn);
 
        while (true) {
            PhoneInfo info = (PhoneInfo) in.readObject();
            if (info == null//read til end of file (null)
                break;
            phoneInfo.add(info);
        }
    } catch (EOFException e) {
    } catch (Exception e) {
    } finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException closeException) {
            closeException.printStackTrace();
        }
    }
}
 

 

 

 

Reference

난 정말 자바를 공부한 적이 없다구요 윤성우 저

http://woowabros.github.io/experience/2017/10/17/java-serialize.html 

https://www.mkyong.com/java/how-to-read-and-write-java-object-to-a-file/ 

'JAVA' 카테고리의 다른 글

Java IOException - Stream Closed  (0) 2019.07.19
Error: could not find or load main class Main  (0) 2019.07.19
for each  (0) 2019.07.13
Returning ArrayList from Method  (0) 2019.07.13
Iterator  (0) 2019.07.12