Scanner 외에 입출력 스트림을 이용해서 구현해 보자
package kosta.io;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
public class BufferedExam {
public static void main(String[] args) {
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new InputStreamReader(System.in));
bw = new BufferedWriter(new FileWriter("output.txt"));
System.out.println("입력 : ");
String str = "";
while(!(str=br.readLine()).equals("q")) {
str += "\n";
bw.write(str);
}
System.out.println("쓰기 완료");
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
bw.close();
br.close();
} catch (Exception e2) {
}
}
}
}
입출력 스트림을 활용해 기존에 생성된 파일의 복사본을 만들어라.
package kosta.io;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
public class BufferedMission {
public static void main(String[] args) {
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader("output.txt"));
bw = new BufferedWriter(new FileWriter("copy.txt"));
String str;
while((str = br.readLine()) != null) {
bw.write(str);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
bw.close();
br.close();
} catch (Exception e2) {
// TODO: handle exception
}
}
}
}
기존 전화번호부 예제를 활용하여 PhoneInfo 객체를 직렬화, 역직렬화를 하여라
또한 프로그램에서 저장, 불러오기를 구현해라.
PhoneInfo.java
package kosta.phone;
import java.io.Serializable;
public class PhoneInfo implements Serializable{ // 직렬화
private String name;
private String phone_number;
private String birth;
public PhoneInfo() {
}
public PhoneInfo(String name, String phone_number, String birth) {
this.name = name;
this.phone_number = phone_number;
this.birth = birth;
}
public void print() {
System.out.println("이름 : "+name);
System.out.println("전화번호 : "+phone_number);
System.out.println("생년월일 : "+birth);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone_number() {
return phone_number;
}
public void setPhone_number(String phone_number) {
this.phone_number = phone_number;
}
public String getBirth() {
return birth;
}
public void setBirth(String birth) {
this.birth = birth;
}
}
Manager.java
public void save() {
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream("list.txt", true));
oos.writeObject(list);
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
oos.close();
} catch (Exception e2) {}
}
System.out.println("파일로 저장 되었습니다.");
}
public void callList() {
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream("list.txt"));
list = (List<PhoneInfo>) ois.readObject();
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
ois.close();
} catch (Exception e2) {}
}
System.out.println("불러오기 완료");
}