본문 바로가기

ANDROID

[안드로이드] 간단한 직렬화, 역직렬화 쓰기(Serialize, Deserialize)

1. 직렬화를 사용할 액티비티 클래스에 Serializable implement


public class MyActivity extends Activity implements Serializable {


...


2. FileOutputStream으로 직렬화한 파일을 저장할 경로와 이름, 확장자를 지정하고


ObjectOutputStream에 직렬화하고자 하는 Object를 writeObject로 추가


try{

FileOutputStream fos= new FileOutputStream(Environment.getExternalStorageDirectory().toString()
+ "파일경로와 파일 이름.확장자");
ObjectOutputStream oos= new ObjectOutputStream(new BufferedOutputStream(fos));
oos.writeObject(ObejctData);
oos.close();
fos.close();
}catch(IOException ioe){
ioe.printStackTrace();
}


.. 직렬화 완료! (파일을 생성하는 중에 권한이 필요할 경우 따로 추가해야 하는 요소들을 넣어줘야 함. 매니페스트부터 권한요청 등)



3. 역직렬화를 수행할 때는 비슷한 방식으로 FileInputStream 으로 불러올 파일의 경로와 이름, 확장자를 넣고


ObjectInputStream으로부터 역직렬화한 Obejct를 적절히 사용.


(아래의 경우 ObjectData라는 자료유형을 가진 Arraylist를 쓰고 불러오는 과정을 수행한 것임)


try{

FileInputStream fis = new FileInputStream(Environment.getExternalStorageDirectory().toString()
+ "파일경로와 파일 이름.확장자");
ObjectInputStream ois = new ObjectInputStream(fis);
ObejctData = (ArrayList<ObejctData>) ois_1.readObject();
ois.close();

} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}


이정도로 복잡하지 않게 직렬화, 역직렬화를 해볼 수 있는데, 권한이나 역직렬화의 경우에도 Serializable을 implement 해주어야 하는지등은


계속 진행하면서 업데이트를 할 예정이다.


Kitkat의 경우에는 따로 권한요청을 받지 않는것으로 보이나 상위 버전부터 저장소를 건드리면 필수적으로 권한이 필요하게 될 수도 있다.




<참조>


http://mainia.tistory.com/2103