문제

My code like below.

Map<String, String> aMap = new HashMap();
aMap.put("A", "a");
FileOutputStream fos = new FileOutputStream(new File("some.txt"));
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.write(aMap);
oos.flush();
oos.close();

I thought I need to close fos, but other says its fine. Is it really fine to not close FileOutputStream, because I already closed inner OutputStream?

도움이 되었습니까?

해결책 2

No you dont need to close FileOutputStream. If you check the code of close() you will found that it closes the output stream.

Plz see the doc http://docs.oracle.com/javase/7/docs/api/java/io/ObjectOutputStream.html

다른 팁

Yes, You don't need to close it separately. If you close your oos, it will internally close fos as well. Closing the outer most stream will delegate it all the way down

You don't need to do this explicitly, it will be done automatically. Take a look at the example from javadoc:

FileOutputStream fos = new FileOutputStream("t.tmp");
  ObjectOutputStream oos = new ObjectOutputStream(fos);

  oos.writeInt(12345);
  oos.writeObject("Today");
  oos.writeObject(new Date());

  oos.close();

The link could be found here: Class ObjectOutputStream

It's a general rule in Java: if you have several chained/nested streams say
outStream3(outStream2(outStream1)) (I am writing this just in pseudo-code) you
usually need to close only the outermost stream - i.e. outStream3 in this case.
Internally when you call close on outStream3, it will call close on outStream2
which will call close on outStream1. There are a few exceptions to this rule, but
this is the general rule you can remember.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top