본문 바로가기

Java

05.17 io 입출력 serializable

20_io_stream.zip
0.07MB
21_object_serial.zip
0.07MB
20230517_java_실습_IO.zip
0.23MB

 

 

다른 프로젝트에서 output한 것을

input하는 경우

패키지 이름,클래스이름까지 같은 직렬화클래스가 있어야 

ClassNotFoundException이 발생하지 않는다.

클래스 이름 =  패키지이름.클래스이름


package f10_object;

import java.io.*;
import java.util.Arrays;

public class ObjectStreamExample {

public static void main(String[] args) {
// dat : 확인할 수 없는 파일(2진으로표현)이라고 알려주는 확장자
try( // try with resources try블럭 끝나면 자동으로 외부자원 해제
FileInputStream fis = new FileInputStream("object.dat");
BufferedInputStream bis = new BufferedInputStream(fis);
ObjectInputStream ois = new ObjectInputStream(bis);

FileOutputStream fos = new FileOutputStream("object.dat");
BufferedOutputStream bos = new BufferedOutputStream(fos);
ObjectOutputStream oos = new ObjectOutputStream(bos);

){
//try
oos.writeObject(new Integer(100));
oos.writeObject(Double.valueOf(3.14));
oos.writeObject(new int[] {1,2,3,4});
oos.writeObject(new String("최기근"));
oos.flush();

Integer obj1 = (Integer)ois.readObject();
Double obj2 = (Double)ois.readObject();
int[] obj3 = (int[])ois.readObject();
String obj4 = (String)ois.readObject();
System.out.println(obj1);
System.out.println(obj2);
System.out.println(Arrays.toString(obj3));
System.out.println(obj4);

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

}

}


 

 

 

package f10_object.serializable;

 

import java.io.Serializable;

 

public class Person implements Serializable{

 

 

private static final long serialVersionUID = 6131082771311808494L;

 

private String name;

// 직렬화 필드에서 제외

transient private int age;

 

private String phone;

 

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public int getAge() {

return age;

}

public void setAge(int age) {

this.age = age;

}

 

 

public String getPhone() {

return phone;

}

public void setPhone(String phone) {

this.phone = phone;

}

@Override

public String toString() {

return "Person [name=" + name + ", phone=" + phone + "]";

}

 

 

 

}


 

package f10_object.serializable;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

public class ObjectOutputStreamAppend extends ObjectOutputStream{

public ObjectOutputStreamAppend(OutputStream out) throws IOException {
super(out);
}

@Override
protected void writeStreamHeader() throws IOException {
// 아무 일도 하지 않음 - 헤더 정보 추가 x
}

}


package f10_object.serializable;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

public class ObjectOutputExample {

public static void main(String[] args) {
File file = new File("C:\\temp\\person");
if(!file.exists()) {
file.mkdirs();
}
file = new File(file,"person.dat");
try {
OutputStream os = new FileOutputStream(file,true);
//이어서 작성하려면 헤더정보가 추가되지 않도록 ObjectOutputStreamAppend 따로 추가해서
// writeStreamHeader 오버라이딩 해줌
ObjectOutputStream oos = null;
if(!file.exists() || file.length() == 0 ) {
System.out.println("New");
oos= new ObjectOutputStream(os);
}else {
System.out.println("Append");
oos= new ObjectOutputStreamAppend(os);
}

Person person = new Person();
person.setName("이순신2");
person.setAge(500);
person.setPhone("01012345678");
oos.writeObject(person);

Person p1 = new Person();
p1.setName("최기근2");
p1.setAge(26);
p1.setPhone("01094867166");
oos.writeObject(p1);
oos.flush();
oos.close();
System.out.println("완료");

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}

 


package f10_object.versionuid;

 

import java.io.Serializable;

 

public class ClassA implements Serializable{

/**

*

*/

private static final long serialVersionUID = -989570321322205133L;

int field1;

int field2;

String name;

 

}


package f10_object.versionuid;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;

public class InputExample {

public static void main(String[] args) {

try {
ObjectInputStream ois
= new ObjectInputStream(new FileInputStream("uid.dat"));
ClassA a = (ClassA)ois.readObject();
System.out.println(a.field1);
System.out.println(a.field2);
System.out.println(a.name);
ois.close();

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}


 

package f10_object.versionuid;

 

import java.io.*;

 

public class OutputExample {

 

public static void main(String[] args) {

 

try {

FileOutputStream fos = new FileOutputStream("uid.dat");

ObjectOutputStream oos = new ObjectOutputStream(fos);

 

ClassA a = new ClassA();

a.field1 = 1;

a.field2 = 3;

oos.writeObject(a);

oos.flush();

oos.close();

 

 

 

 

} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

 

}


package f10_object.serializable;

 

import java.io.Serializable;

 

public class Person implements Serializable{

 

 

private static final long serialVersionUID = 6131082771311808494L;

 

private String name;

private int age;

 

 

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public int getAge() {

return age;

}

public void setAge(int age) {

this.age = age;

}

 

 

 

@Override

public String toString() {

return "Person [name=" + name + ", age=" + age + "]";

}

 

 

 

 

}


package f10_object.serializable;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.List;

public class InputExample {

public static void main(String[] args) {
File file = new File("C:\\Temp\\person\\person.dat");
if(!file.exists()) {
System.out.println("파일이 존재하지 않습니다. 확인 후 시도하세요.");
return;
}
try {
InputStream fis = new FileInputStream(file);
System.out.println(fis.available());
ObjectInputStream ois = new ObjectInputStream(fis);
System.out.println(ois.available());
List<Person> pList = new ArrayList<>();
while(fis.available() != 0) {
Person p = (Person) ois.readObject();
pList.add(p);
}

System.out.println(pList.size());
System.out.println(pList);
ois.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}

'Java' 카테고리의 다른 글

05.19 스레드,네트워크  (0) 2023.05.23
05.18 람다표현식, 스레드  (0) 2023.05.18
05.16. IO기반 입출력  (0) 2023.05.16
05.12실습  (0) 2023.05.12
05.11 컬렉션 프레임워크  (0) 2023.05.11