JAVA
Java IOException - Stream Closed
seoca
2019. 7. 19. 08:27
file.close() should be outside of while loop otherwise java.io.EOFException occur.
You should place close() in finally.
public void readFile() throws ClassNotFoundException {
if (!dataFile.exists()) //생성한 파일이 존재하지 않으면 return
return;
ObjectInputStream in = null; //try 구문 바깥에 선언해줘서 다른 scope 에서도 사용가능하게 해준다!
try {
BufferedInputStream fileIn = new BufferedInputStream (new FileInputStream(dataFile));
//FileInputStream : 파일로부터 바이트단위의 데이터를 읽거나 파일에 바이트 데이터를 저장할 수 있다.
//BufferedInputStream : 처리할 데이터가 많으면 부하를 일으킬 수 있으므로 buffer 를 사용한다.
//FileReader : 문자단위로 데이터를 처리.
if (fileIn == null) {
throw new IOException("Can't find file.");
}
in = new ObjectInputStream(fileIn); //ObjectInputStream :
while (true) {
PhoneInfo info = (PhoneInfo) in.readObject(); // 어쨌든 Object를 읽어와야 되니까
if (info == null) //read til end of file (null)
break;
phoneInfo.add(info);
}
} catch (EOFException e) {
// e.printStackTrace(); -이것도 괜히 따라 넣었다가 에러남
} catch (Exception ex) {
} finally {
try {
if (in != null) { //존재하지도 않는 파일을 닫으려고하면 error가 발생한다. 그래서 null check를 꼭 해주어야 한다.
in.close(); //You should always close in a finally block.
}
} catch (IOException closeException) {
closeException.printStackTrace();
}
}
}
|
Reference
https://stackoverflow.com/questions/16646978/exception-with-objectinputstream-while-reading-and-reaching-the-end-of-the-file - so much helpful one
https://stackoverflow.com/questions/25294321/why-check-for-not-null-before-closing-fileoutputstream
https://stackoverflow.com/questions/32943897/java-ioexception-stream-closed