[Java] 직렬화 Serializable, Stream - Data,File,Object

package day0226;

 

import java.io.DataInputStream;

import java.io.DataOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

 

import javax.swing.JOptionPane;

 

public class UseDataStream {

public void useDataOutputStream(File file) {

int age=25;

 

//자바의 기본형 데이터 형을 내보낼 수 있는 Stream 연결

try(DataOutputStream dos=new DataOutputStream(new FileOutputStream(file))) {

//스틤에 데이터 기록

dos.writeInt(age);

//스트림에 내용을 분출

dos.flush();

 

} catch (IOException ie) {

ie.printStackTrace();

}

}//seDataOutputStream

 

public void useDataInputStream(File file) {

 

//데이터를 읽어들기위한 Stream 생성

try(DataInputStream dis

=new DataInputStream(new FileInputStream(file))) {

//스트림에서 데이터 읽기

int data=dis.readInt();

System.out.println("읽어들인 데이터 "+ data);

}catch (IOException ie) {

ie.printStackTrace();

}

}//end catch

 

public static void main(String[] args) {

UseDataStream uds=new UseDataStream();

File file=new File("c:/dev/temp/data_output.txt");

switch(JOptionPane.showConfirmDialog(null, "데이터를 JVM 외부로 내보내시겠습니까?")) {

case JOptionPane.OK_OPTION:

uds.useDataOutputStream(file);

break;

case JOptionPane.NO_OPTION:

switch (JOptionPane.showConfirmDialog(null,"데이터를 JVM내부로 읽어들이시겠습니까?")) {

case JOptionPane.OK_OPTION:

uds.useDataInputStream(file);

}

 

}

 

}//main

 

}//class

컴파일 결과

package day0226;

import java.io.File;

import java.io.FileOutputStream;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.ObjectOutputStream;

 

import javax.swing.JOptionPane;

 

import java.io.ObjectInputStream;

 

public class UseObjectStream {

public void writeObject(File file, UserDataVO udVO) throws IOException {

ObjectOutputStream oos = null;

try {

// 1. 객체를 내보낼 수 있는 스트림 생성

oos = new ObjectOutputStream(new FileOutputStream(file));

// 2. 객체를 잘라서 내보내기 (객체 직렬화)

oos.writeObject(udVO);

// 3.스트림에 안의 내용을 목적지로 분출

oos.flush();

} finally {

if (oos != null) {

oos.close();

}

}

}

 

public UserDataVO readObject(File file) throws IOException, ClassNotFoundException {

UserDataVO udVO = null;

ObjectInputStream ois = null;

try {

// 스트림 연결

ois = new ObjectInputStream(new FileInputStream(file));

// 객체 읽기

udVO = (UserDataVO) ois.readObject();

} finally {

if (ois != null) {

ois.close();

}

}

return udVO; // 메서드 종료

} // end readObject

 

public static void main(String[] args) {

String inputMenu = JOptionPane.showInputDialog("아래의 번호를 입력\n 1-객체쓰기, 2-객체 읽기");

UseObjectStream uos = new UseObjectStream();

if (inputMenu != null) {

File file = new File("c:/dev/temp/obj.txt");

if ("1".equals(inputMenu)) {

UserDataVO udVO = new UserDataVO("강태일", 185.7, 74.2);

try {

uos.writeObject(file, udVO);

System.out.println("객체 쓰기 완료: " + udVO);

} catch (IOException ie) {

ie.printStackTrace();

}

}

if ("2".equals(inputMenu)) {

try {

UserDataVO udVO = uos.readObject(file);

System.out.println("객체의 값 읽기: " + udVO);

} catch (IOException e) {

e.printStackTrace();

}catch (ClassNotFoundException e) {

e.printStackTrace();

}//end catch

}

 

}

}

}

package day0226;

 

import java.io.Serializable;

 

//내가 만든걸로 인증해 라고 워닝 뜨는거임ㅇㅇ

public class UserDataVO implements Serializable {//이파일이 스트림 타고 쪼개져서 저장

/**

*

*/

private static final long serialVersionUID = 5246131094299996868L;

// 나는 잘려질수있어.

 

private transient String name;//이름을 숨긴다 직렬화를 막음.

private /*transient*/ double height;

private double weight;

 

public UserDataVO(String name, double height, double weight) {

super();

this.name = name;

this.height = height;

this.weight = weight;

}

 

public String getName() {

return name;

}

 

public void setName(String name) {

this.name = name;

}

 

public double getHeight() {

return height;

}

 

public void setHeight(double height) {

this.height = height;

}

 

public double getWeight() {

return weight;

}

 

public void setWeight(double weight) {

this.weight = weight;

}

 

@Override

public String toString() {

return "UserDataVO [name=" + name + ", height=" + height + ", weight=" + weight + "]";

}

}

컴파일 결과

package day0226;

 

import java.io.File;

import java.io.IOException;

import java.nio.file.Files;

import java.nio.file.Path;

import java.nio.file.Paths;

import java.util.List;

 

import javax.swing.JFileChooser;

import javax.swing.JOptionPane;

import javax.swing.JScrollPane;

import javax.swing.JTextArea;

 

public class UseNioFile {

 

public UseNioFile() throws IOException {

 

JFileChooser jfc=new JFileChooser();

jfc.showOpenDialog(null);

 

File selectedfile=jfc.getSelectedFile();

 

if(selectedfile == null) {

return;

}//end if

 

//N I/O를 사용한 파일 내용 읽기

//1. Path 얻기

Path path=Paths.get( selectedfile.getAbsolutePath() );

System.out.println(path);

//2.파일의 모든 내용을 읽어 들임

List<String> allLines=Files.readAllLines(path);

 

StringBuilder output=new StringBuilder();

//읽어 들인 파일의 내용을 출력하기 위해 StringBuilder에 저장

for(String line : allLines) {

output.append(line).append("\n");

}//end for

 

JTextArea jta=new JTextArea(output.toString(),40,80);

JScrollPane jsp=new JScrollPane(jta);

JOptionPane.showMessageDialog(null, jsp);

 

}//UseNioFile

 

public static void main(String[] args) {

try {

new UseNioFile();

} catch (IOException e) {

e.printStackTrace();

}//end catch

 

}//main

 

}//class

컴파일 시 파일탐색기가 열림

package day0226;

 

import java.io.NotSerializableException;

import java.io.Serializable;

 

public class UseInstanceOf {

 

public void useInstanceOf(Test t) throws NotSerializableException {

if(t instanceof Serializable) {

System.out.println("직렬화 가능");

}else{

// System.out.println("직렬화 불가능");

throw new NotSerializableException("생명연장의 꿈");

}//else

 

}

public static void main(String[] args) {

Test t=new Test();

UseInstanceOf uio=new UseInstanceOf();

try {

uio.useInstanceOf(t);

} catch (NotSerializableException e) {

e.printStackTrace();

}

}

 

}

콘솔 출력

직렬화 가능