package day18.api.io.obj;
import java.io.Serializable;
public class Human implements Serializable {
//객체를 파일에 저장하려면 객체를 직렬화해야 하는데
// Serializable 인터페이스를 구현해야 합니다.
private String name;
private int age;
private String address;
public Human(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
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 getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Human{" +
"name='" + name + '\'' +
", age=" + age +
", address='" + address + '\'' +
'}';
}
}
package day18.api.io.obj;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class Main {
static List<Human> humanList = new ArrayList<>();
public static void main(String[] args) {
humanList.add(new Human("김철수", 22, "서울시 금천구"));
humanList.add(new Human("박영희", 24, "서울시 금천구"));
humanList.add(new Human("홍길동", 45, "서울시 중구"));
// svaeTextFile();
saveObject();
}
// 고전적 방법보다 간단한 방법으로 저장하기 (객체 세이브 기능 )
static void saveObject(){
// 리스트를 통째로 세이브 파일로 보내기
try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("E:/Exercise/human.sav"))) {
oos.writeObject(humanList); // 객체를 저장하려면 데이터를 바이트 형태로 직렬화 해야 한다.
// 휴먼이 직렬화 되어 있지 않다는 에러 발생
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// 텍스트 파일로 저장하는 고전적인 방법 (7~80년대)
// 세이브 기능
/*static void svaeTextFile(){
try(FileWriter fw = new FileWriter("E:/Exercise/human.txt")){
StringBuilder sb = new StringBuilder();
for (Human h : humanList) {
fw.write(String.format("%s,%d,%s\r\n",h.getName(),h.getAge(),h.getAddress()));
}
System.out.println("저장완료");
} catch (IOException e) {
e.printStackTrace();
}
}*/
}
package day18.api.io.obj;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class Main2 {
static List<Human> humanList = new ArrayList<>();
public static void main(String[] args) {
// loadTextFile();
loadObject();
for (Human h : humanList) {
System.out.println(h);
}
}
// 세이브 파일 불러와서 리스트에 넣기
static void loadObject(){
try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream("E:/Exercise/human.sav"))) {
humanList = (List<Human>) ois.readObject(); // 다운 캐스팅
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
// 텍스트 파일 불러와서 리스트에 넣기 (로드)
static void loadTextFile(){
try(BufferedReader br = new BufferedReader(new FileReader("E:/Exercise/human.txt"))){
String s = "";
while((s = br.readLine()) != null) {
// human 객체에 다시 넣기
StringTokenizer st = new StringTokenizer(s,",");
Human human = new Human(st.nextToken(), Integer.parseInt(st.nextToken()),st.nextToken());
humanList.add(human);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
'JAVA' 카테고리의 다른 글
java_람다_22.06.20(day20) (0) | 2022.06.20 |
---|---|
java_익명 클래스(anonymous)_22.06.17(day19) (0) | 2022.06.20 |
java_입출력(Stream,reader,writer,보조스트림)_22.06.17(day19) (0) | 2022.06.17 |
java_컬렉션_실습예제_22.06.16(day18) (0) | 2022.06.16 |
java_컬렉션(Map)_22.06.16(day18) (0) | 2022.06.16 |