티스토리 뷰
Reading and Writing Java Object to a file in java
//Serialization 직렬화 - Object 자체를 file 에 저장하고 싶을 때 사용. 이 클래스를 상속하는 하위클래스들도 직렬화가 가능해진다.
public class PhoneInfo implements Serializable {
...
}
|
public class PhoneManager {
private final File dataFile = new File("PhoneBook.txt"); //create file
...
public void storeFile(){
FileOutputStream file = null;
try {
file = new FileOutputStream(dataFile);
try {
ObjectOutputStream out = new ObjectOutputStream(file); //converted into byte-stream
Iterator<PhoneInfo> itr = phoneInfo.iterator();
while(itr.hasNext())
out.writeObject(itr.next());
out.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public void readFile() throws ClassNotFoundException {
if (!dataFile.exists())
return;
ObjectInputStream in = null;
try {
FileInputStream fileIn = new FileInputStream(dataFile);
if (fileIn == null) {
throw new IOException("Can't find file.");
}
in = new ObjectInputStream(fileIn);
while (true) {
PhoneInfo info = (PhoneInfo) in.readObject();
if (info == null) //read til end of file (null)
break;
phoneInfo.add(info);
}
} catch (EOFException e) {
} catch (Exception e) {
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException closeException) {
closeException.printStackTrace();
}
}
}
|
Reference
난 정말 자바를 공부한 적이 없다구요 윤성우 저
http://woowabros.github.io/experience/2017/10/17/java-serialize.html
https://www.mkyong.com/java/how-to-read-and-write-java-object-to-a-file/
'JAVA' 카테고리의 다른 글
Java IOException - Stream Closed (0) | 2019.07.19 |
---|---|
Error: could not find or load main class Main (0) | 2019.07.19 |
for each (0) | 2019.07.13 |
Returning ArrayList from Method (0) | 2019.07.13 |
Iterator (0) | 2019.07.12 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- javascript
- easy algorithm
- math.max
- 알고리즘
- 프로그래머스
- C++
- Collection Framework
- 프로그래머스 알고리즘
- math.abs
- compareTo()
- java
- spring boot application
- repeat()
- code refactoring
- hackerrank
- hackerrank javascript solution
- Javascript Algorithm
- equals()
- string class in java
- substring()
- hackerrank solution
- HashMap
- easy javascript algorithm
- ... in Javascript
- HackerRank Algorithm
- rest parameter
- algorithm
- 프로그래머스 알고리즘문제
- hackerrank javascript
- Object type casting
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
글 보관함