본문 바로가기
Web & Mobile/JAVA

Lecture 31 - Java(12) DataInputStream, DataOutputStream, PrintStream, System.in, out, err, Menu, RandomAccessFile, ObjectInputStream, ObjectOutputStream

by Bennyziio 2023. 6. 20.
반응형

DataInputStream과 DataOutputStream
: DataInputStream/DataOutputStream도 각각 FilterInputStream/FilterOutputStreamm의 자손이며 DataInputStream은 DataInput 인터페이스를, DataOutputStream은 DataOutput 인터페이스를 각각 구현하였기 때문에, 데이터를 읽고 쓰는데 있어서 byte단위가 아닌, 8가지 기본 자료형의 단위로 읽고 쓸 수 있다는 장점이 있다.
DataOutputStream이 출력하는 형식은 각 기본 자료형 값을 16진수로 표현하여 저장한다. 예를 들어 int값을 출력한다면, 4byte의 16진수로 출력된다.

DataOutputStreamEx01 - utf-8 방식으로 저장

import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class DataOutputStreamEx01 {

	public static void main(String[] args) {
		
		DataOutputStream dos = null;
		
		try {
			dos = new DataOutputStream(new FileOutputStream("c:/Java/value.dat"));
			
			dos.writeInt(2018);
			dos.writeUTF("utf-8 형식으로 저장");
			dos.writeFloat(1.0f);
			
			System.out.println("출력완료");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(dos != null) {try {dos.close();} catch (IOException e) {e.printStackTrace();}}
		}
	}
}

DataInputStreamEx01- utf-8 방식으로 저장한것을 읽어오기

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

public class DataInputStreamEx01 {

	public static void main(String[] args) {

		DataInputStream dis = null;
		
		try {
			dis = new DataInputStream(new FileInputStream("c:/Java/value.dat"));
			
			System.out.println(dis.readInt());
			System.out.println(dis.readUTF());
			System.out.println(dis.readFloat());
			
			System.out.println("출력 완료");
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(dis != null) {try {dis.close();} catch (IOException e) {e.printStackTrace();}}
		}
		
	}

}

DataOutputStreamEx03

import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class DataOutputStreamEx03 {

	public static void main(String[] args) {
		int[] score = {100, 90, 95, 85, 50};
		FileOutputStream fos = null;
		DataOutputStream dos = null;
		
		try {
			fos = new FileOutputStream("c:/Java/score.dat");
			dos = new DataOutputStream(fos);
			
			for(int i=0; i<score.length; i++) {
				dos.writeInt(score[i]);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(dos != null) {try {dos.close();} catch (IOException e) {e.printStackTrace();}}
		}
	}
}

DataInputStreamEx02

import java.io.DataInputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class DataInputStreamEx02 {

	public static void main(String[] args) {

		int sum = 0;
		int score = 0;
		
		FileInputStream fis = null;
		DataInputStream dis = null;
		
		try {
			fis = new FileInputStream("c:/Java/score.dat");
			dis = new DataInputStream(fis);
			
			while(true) {
				score = dis.readInt();
				System.out.println(score);
				sum += score;
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (EOFException e) {
			System.out.println("점수의 총합은 " + sum +"입니다");
		} catch (IOException ie) {
			ie.printStackTrace();
		} finally {
			//if(fis != null) {try {fis.close();} catch (IOException e) {e.printStackTrace();}}
			if(dis != null) {try {dis.close();} catch (IOException ie) {ie.printStackTrace();}}
		}
	}
}

출력한 값들은 이진 데이터(binary data)로 저장 된다. 문자 데이터(text data)가 아니므로 문서 편집기로 열어봐도 알 수 없는 글자들로 이루어져 있다. 파일을 16진수 코드로 볼 수 있는 UltraEdit과 같은 프로그램이나 ByteArrayOutputStream을 사용하면 이진데이터를 확인할 수 있다

PrintStream
: PrintStream은 데이터를 기반스트림에 다양한 형태로 출력할 수 있는 print, println, printf와 같은 메서드를 오버로딩하여 제공한다.
PrintStream은 데이터를 적절한 문자로 출력하는 것이기 때문에 문자기반 스트림의 역활을 수행한다.
printf()는 JDK1.5부터 추가된 것으로, C언어와 같이 편리한 형식화된 출력을 지원하게 되었다.

PrintStreamEx01 - printf 출력 format별 예제

import java.util.Date;

public class PrintStreamEx01 {

	public static void main(String[] args) {

		int i = 65;
		float f = 1234.56789f;
		
		Date d = new Date();
		
		System.out.printf("문자 %c의 코드는 %d%n", i, i);
		System.out.printf("%d는 8진수로 %o, 16진수로 %x%n", i, i, i);
		System.out.printf("%3d%3d%3d\n", 100, 90, 80);
		System.out.println();
		System.out.printf("123456789012345678901234567890%n");
		System.out.printf("%s%-5s%5s%n", "123", "123", "123");
		System.out.println();
		System.out.printf("%-8.1f%8.1f %3%n", f, f, f);
		System.out.println();
		System.out.printf("오늘은 %tY년 %tm월 %td일 입니다.%n", d, d, d);
		System.out.printf("지금은 %tH시 %tM분 %tS초 입니다.%n", d, d, d);
		System.out.printf("지금은 %1$tH시 %1$tM분 %1$tS초 입니다. %n", d);
	}

}

표준입출력 - System.in, System.out, System.err
표준입출력은 콘솔(console, 도스창)을 통한 데이터 입력과 콘솔로의 데이터 출력을 의미한다. 자바에서는 표준 입출력(standard I/O)을 위해 3가지 입출력 스트림, System.in, System.out, System.err을 제공하는데, 이 들은 자바 어플리케이션의 실행과 동시에 사용할 수 있게 자동적으로 생성되기 때문에 개발자가 별도로 스트림을 생성하는 코드를 작성하지 않고도 사용이 가능하다.

System.in 콘솔로부터 데이터를 입력받는데 사용
System.out 콘솔로 데이터를 출력하는데 사용
System.err 콘솔로 데이터를 출력하는데 사용(자주 사용은 안한다)

SystemInEx01

import java.io.IOException;
import java.io.InputStream;

public class SystemInEx01 {

	public static void main(String[] args) {

		InputStream is = null;
		
		try {
			is = System.in;
			System.out.print("입력 : ");
			
			int data = is.read();
			System.out.println("값 : " + (char)data);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if(is != null) try {is.close();} catch(IOException e) {};
		}
		
	}

}

import java.io.IOException;
import java.io.InputStream;

public class SystemInEx01 {

	public static void main(String[] args) {

		InputStream is = null;
		
		try {
			is = System.in;
			System.out.print("입력 : ");
			
			int data = is.read();
			System.out.println("값 : " + (char)data);
			
			data = is.read();
			System.out.println("값 : " + (char)data);
			
			data = is.read();
			System.out.println("값 : " + (char)data);
			
			data = is.read();
			System.out.println("값 : " + (char)data);
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if(is != null) try {is.close();} catch(IOException e) {};
		}
		
	}

}

4개를 읽고 싶을때

import java.io.IOException;
import java.io.InputStream;

public class SystemInEx01 {

	public static void main(String[] args) {

		InputStream is = null;
		
		try {
			is = System.in;
			System.out.print("입력 : ");
			
			int data = 0;
			// enter 키까지 읽는다
			while((data = is.read())!= 13) {
				System.out.print((char)data);
			}
			System.out.println();
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if(is != null) try {is.close();} catch(IOException e) {};
		}
		
	}

}

enter 키까지 읽고 싶을 때

SystemInEx2

import java.io.IOException;
import java.io.InputStreamReader;

public class SystemInEx2 {

	public static void main(String[] args) {

		InputStreamReader isr = null;
		
		try {
			isr = new InputStreamReader(System.in);
			
			System.out.print("입력 : ");
			System.out.println((char)isr.read());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if(isr != null) try {isr.close();} catch (IOException e) {};
		}
		
	}
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class SystemInEx2 {

	public static void main(String[] args) {

		InputStreamReader isr = null;
		BufferedReader br = null;
		
		try {
			isr = new InputStreamReader(System.in);
			br = new BufferedReader(isr);
			
			System.out.print("입력 : ");
			System.out.println("값 : " + br.readLine());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(isr != null) try {isr.close();} catch (IOException e) {};
			if(br != null) try {br.close();} catch (IOException e) {};
		}
	}
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class SystemInEx2 {

	public static void main(String[] args) {

		InputStreamReader isr = null;
		BufferedReader br = null;
		
		try {
			//isr = new InputStreamReader(System.in);
			//br = new BufferedReader(isr);
			br = new BufferedReader(new InputStreamReader(System.in));
			System.out.print("입력 : ");
			System.out.println("값 : " + br.readLine());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(isr != null) try {isr.close();} catch (IOException e) {};
			if(br != null) try {br.close();} catch (IOException e) {};
		}
	}
}

실행
1. IO
2. scanner

* 종료 전까지 무한 루프(while)

== 메뉴 ======
1. 조회
2. 삽입
3. 수정
4. 삭제
5. 종료

메뉴를 선택하세요 : 

MenuEx01 - 위 메뉴 선택창 만들기

import java.io.IOException;
import java.io.InputStream;

public class MenuEx01 {

	public static void main(String[] args) {

		System.out.println("== 메뉴 ==");
		System.out.println("1. 조회");
		System.out.println("2. 추가");
		System.out.println("3. 제거");
		System.out.println("4. 종료");

		System.out.println("메뉴를 선택하세요 : ");
		
		InputStream is = null;
		
		try {
			is = System.in;
			
			char input = (char)is.read();
			
			switch(input) {
			case '1' : 
				System.out.println("조회 선택");
				break;
			case '2' : 
				System.out.println("추가 서택");
				break;
			case '3' : 
				System.out.println("제거 선택");
				break;
			case '4' : 
				System.out.println("종료 선택");
				break;
			default :
				System.out.println("다시 선택하세요");
				break;
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(is != null) try {is.close();} catch(IOException e) {};
		}
		
	}

}

MenuEx02 - 메뉴 선택을 연속적으로 사용할 수 있게

import java.io.IOException;
import java.io.InputStream;

public class MenuEx02 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
	
		InputStream is = null;
		
		is = System.in;			
		try {
			end:	// label : case 4에 break end라고 되어있어 종료를 
            		// 선택하면 라벨 지정된 곳으로 return된다
			while(true) {
				System.out.println("== 메뉴 ==");
				System.out.println("1. 조회");
				System.out.println("2. 추가");
				System.out.println("3. 제거");
				System.out.println("4. 종료");
				
				System.out.print("\n메뉴를 선택하세요 : ");
				
				char input = (char)is.read();
				is.read();is.read();	// 엔터키를 인식하지 못해 엔터키를 자동으로 
                						// 넣어주는것으로 두번 엔터키 넣어주는 것
				
				switch(input) {
				case '1' :
					System.out.println("\n조회 선택");
					break;
				case '2' :
					System.out.println("\n추가 선택");
					break;
				case '3' :
					System.out.println("\n제거 선택");
					break;	
				case '4' :
					System.out.println("\n종료 선택");
					break end;
				default :
					System.out.println("\n다시 선택하세요");
					break;
				}
			}	
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (is != null) try { is.close(); } catch (IOException e) {}
		}
		
	}
}

RandomAccessFile
: 자바에서는 입력과 출력이 각각 분리되어 별도로 작업을 하도록 설계되어 있는데, RandomAccessFile만은 하나의 클래스로 파일에 대한 입력과 출력을 모두 할 수 있도록 되어 있다. InputStream이나 OutPutStream으로부터 상속받지 않고, DataInput인터페이스와 DataOutput인터페이스를 모두 구현했기 때문에 읽기와 쓰기가 모두 가능하다.
RandomAccessFile클래스의 가장 큰 장점은 파일의 어느 위치에나 읽기/쓰기가 가능하다는 것이다. 다른 입출력 클래스들은 입출력소스에 순차적으로 읽기/쓰기를 하기 때문에 읽기와 쓰기가 제한적인데 반해서 RandomAccessFile클래스는 파일에 읽고 쓰는 위치에 제한이 없다.
현재 작업중인 파일에서 파일 포인터의 위치를 알고 싶을 때는 getFilePointer()를 사용하면 되고, 파일 포인터의 위치를 옮기기 위해서는 seek(long pos)나 skipBytes(int n)를 사용하면 된다.

RandomAccessFileEx01

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

public class RandomAccessFileEx01 {

	public static void main(String[] args) {

		RandomAccessFile raf = null;
		
		try {
			raf = new RandomAccessFile("test.dat", "rw");
			System.out.println("파일 포인터의 위치 : " + raf.getFilePointer());
			raf.writeInt(100);
			System.out.println("파일 포인터의 위치 : " + raf.getFilePointer());
			raf.writeLong(100L);
			System.out.println("파일 포인터의 위치 : " + raf.getFilePointer());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(raf != null) try {raf.close();} catch(IOException e) {};
		}
		
	}

}

위 예제는 파일에 출력작업이 수행되었을 때 파일 포인터의 위치가 어떻게 달라지는지에 대해서 보여 준다. int가 4 byte이기 때문에 writeInt()를 호출한 다음 파일 포인터의 위치가 0에서 4로 바뀐 것을 알 수 있다. 마찬가지로 8 byte인 long을 출력하는 writeLong()을 호출한 후에는 파일 포인터의 위치가 4에서 12로 변경된 것을 알 수 있다.

RandomAccessFileEx02

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

public class RandomAccessFileEx02 {

	public static void main(String[] args) {

		RandomAccessFile raf = null;
		
		try {
			raf = new RandomAccessFile("c:/Java/data.dat", "rw");
			
			String name = "tester";
			int age = 44;
			double weight = 71;
			
			System.out.println("pointer : " + raf.getFilePointer());
			
			raf.writeUTF(name);
			raf.writeInt(age);
			raf.writeDouble(weight);
			
			System.out.println("pointer : " + raf.getFilePointer());
			System.out.println("저장완료");
			
			raf.seek(0);	// 파일 포인터의 위치를 변경한다 - 0 -> 20으로 갔는데 이걸 다시 0으로 위치 이동
			
			String reName = raf.readUTF();
			int reAge = raf.readInt();
			double reWeight = raf.readDouble();
			
			System.out.println(reName);
			System.out.println(reAge);
			System.out.println(reWeight);
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(raf != null) try {raf.close();} catch(IOException e) {};
		}
		
	}

}

직렬화(Serialization)
: 직렬화(serialization)란 객체를 데이터 스트림으로 만드는 것을 뜻한다. 객체에 저장된 데이터를 스트림에 쓰기(write)위해 연속적인(serial) 데이터로 변환하는 것을 말한다.
반대로 스트림으로부터 데이터를 읽어서 객체를 만드는 것을 역질렬화(deserialization)라고 한다.

ObjectInputStream, ObjectOutputStream
: 직렬화(스트림에 객체를 출력)에는 ObjectOutputStream을 사용하고 역질렬화(스트림으로부터 객체를 입력)에는 ObjectInputStream을 사용한다.

ObjectOutputStreamEx01

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

public class ObjectOutputStreamEx01 {

	public static void main(String[] args) {

		ObjectOutputStream oos = null;
		
		try {
			oos = new ObjectOutputStream(new FileOutputStream("c:/Java/object.dat"));
			
			String[] name = {"홍길동", "박문수"};
			int[] ages = {55, 23};
			double[] weights = {71.4, 67.9};
			int team = 10;
			
			oos.writeObject(name);	// 배열이라서 Object형태로 넣는다
			oos.writeObject(ages);
			oos.writeObject(weights);
			oos.writeInt(team);	// int이므로 int형태로 넣는다
			
			System.out.println("출력 완료");
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(oos != null) try {oos.close();} catch(IOException e) {};
		}
		
	}

}

ObjectInputStreamEx01

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

public class ObjectInputStreamEx01 {

	public static void main(String[] args) {

		ObjectInputStream ois = null;
		
		try {
			ois = new ObjectInputStream(new FileInputStream("c:/Java/object.dat"));
			
			String[] names = (String[])ois.readObject();
			
			for(String name : names) {
				System.out.println(name);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(ois != null) try {ois.close();} catch(IOException e) {};
		}
		
	}

}

ObjectOutputStreamEx2

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

public class ObjectOutputStreamEx2 {

	public static void main(String[] args) {

		ObjectOutputStream oos = null;
		
		try {
			oos = new ObjectOutputStream(new FileOutputStream("c:/Java/object.dat"));
			
			Person p = new Person("홍길동", "010-111-1111", "20");
			oos.writeObject(p);
			
			System.out.println("출력 완료");
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(oos != null) try {oos.close();} catch(IOException e) {};
		}
	}
}
import java.io.Serializable;

public class Person implements Serializable{
	private String name;
	private String phone;
	private String age;
	
	public Person(String name, String phone, String age) {
		this.name = name;
		this.phone = phone;
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public String getPhone() {
		return phone;
	}

	public String getAge() {
		return age;
	}
}

Person class 에서 implements Serializable을 추가해주면 기존에 떴던 java.io.NotSerializableException: Person 오류를 해결할 수 있다. 
아무리 복잡한 멤버들도 위와 같이 하면 해결 가능하다

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

public class ObjectOutputStreamEx2 {

	public static void main(String[] args) {

		ObjectOutputStream oos = null;
		
		try {
			oos = new ObjectOutputStream(new FileOutputStream("c:/Java/object.dat"));
			
			Person p1 = new Person("홍길동", "010-111-1111", "20");
			Person p2 = new Person("박문수", "010-222-2222", "30");
			Person p3 = new Person("이몽룡", "010-333-3333", "40");

			oos.writeObject(p1);
			oos.writeObject(p2);
			oos.writeObject(p3);
			
			System.out.println("출력 완료");
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(oos != null) try {oos.close();} catch(IOException e) {};
		}
	}
}

ObjectInputStreamEx2

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

public class ObjectInputStreamEx2 {

	public static void main(String[] args) {

		ObjectInputStream ois = null;
		
		try {
			ois = new ObjectInputStream(new FileInputStream("c:/Java/object.dat"));
			
			Person p = (Person)ois.readObject();
			
			System.out.println(p.getName());
			System.out.println(p.getPhone());
			System.out.println(p.getAge());
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(ois != null) try {ois.close();} catch(IOException e) {};
		}
	}
}

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

public class ObjectInputStreamEx2 {

	public static void main(String[] args) {

		ObjectInputStream ois = null;
		
		try {
			ois = new ObjectInputStream(new FileInputStream("c:/Java/object.dat"));
			
			// EOFException
			while(true) {
				Person p = (Person)ois.readObject();
				
				System.out.println(p.getName());
				System.out.println(p.getPhone());
				System.out.println(p.getAge());
			}
		} catch (EOFException e) {
			System.out.println("파일 리딩 끝");
			System.out.println("후처리");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(ois != null) try {ois.close();} catch(IOException e) {};
		}
	}
}

transient 사용 - 객체직렬화(Serialization)

import java.io.Serializable;

public class Person implements Serializable{
	private String name;
	private String phone;
	private String age;
	
	transient private String address;
	
	public Person(String name, String phone, String age, String address) {
		this.name = name;
		this.phone = phone;
		this.age = age;
		this.address = address;
	}

	public String getName() {
		return name;
	}

	public String getPhone() {
		return phone;
	}

	public String getAge() {
		return age;
	}

	public String getAddress() {
		return address;
	}
	
}
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class ObjectOutputStreamEx2 {

	public static void main(String[] args) {

		ObjectOutputStream oos = null;
		
		try {
			oos = new ObjectOutputStream(new FileOutputStream("c:/Java/object.dat"));
			
			Person p1 = new Person("홍길동", "010-111-1111", "20", "서울");
			Person p2 = new Person("박문수", "010-222-2222", "30", "경기");
			Person p3 = new Person("이몽룡", "010-333-3333", "40", "부산");

			oos.writeObject(p1);
			oos.writeObject(p2);
			oos.writeObject(p3);
			
			System.out.println("출력 완료");
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(oos != null) try {oos.close();} catch(IOException e) {};
		}
		
	}

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

public class ObjectInputStreamEx2 {

	public static void main(String[] args) {

		ObjectInputStream ois = null;
		
		try {
			ois = new ObjectInputStream(new FileInputStream("c:/Java/object.dat"));
			
			// EOFException
			while(true) {
				Person p = (Person)ois.readObject();
				
				System.out.println(p.getName());
				System.out.println(p.getPhone());
				System.out.println(p.getAge());
				System.out.println(p.getAddress());
			}
		} catch (EOFException e) {
			System.out.println("파일 리딩 끝");
			System.out.println("후처리");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(ois != null) try {ois.close();} catch(IOException e) {};
		}
	}
}

결과를 보면 getAddress는 null값으로 나온다. transient를 사용했기 때문에 Serializatin되지 않았다. 즉, 데이터를 저장하기 싫을때 사용한다(password 같은 거)

직렬화가능한 클래스의 버전관리

import java.io.Serializable;

public class Person implements Serializable{ // 버전
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String name;
	private String phone;
	private String age;
	
	transient private String address;
	
	public Person(String name, String phone, String age, String address) {
		this.name = name;
		this.phone = phone;
		this.age = age;
		this.address = address;
	}

	public String getName() {
		return name;
	}

	public String getPhone() {
		return phone;
	}

	public String getAge() {
		return age;
	}

	public String getAddress() {
		return address;
	}
	
}

빨간 박스안에 add를 하면 versionID가 자동 생성된다

SystemCommandEx01

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

public class SystemCommandEx01 {

	public static void main(String[] args) {

		BufferedReader br = null;
		
		try {
			Process process = new ProcessBuilder("ipconfig").start();
			br = new BufferedReader(new InputStreamReader(process.getInputStream(), "ms949"));
			
			String sentence = null;
			int i = 1;			
			while((sentence = br.readLine()) != null) {
				System.out.println(i++ + ": " + sentence);
			}
			
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(br != null) try {br.close();} catch(IOException e) {};
		}
	}
}

 

 

 

반응형

댓글