开发者

Way to close specific output streams

Do you think this code close correctly the output stream entry ? Knowing that this is not the same type of output stream.

OutputStream out = new JarOutputStream(new FileInputstrem(fileName));
        开发者_JS百科               ...
((ZipOutputStream)out).closeEntry();

But considering that the both are output stream, I thought they were closing in the same way. And therefore in my case ((ZipOutputStream)out).closeEntry(); was the same as ((JarOutputStream)out).closeEntry();

Can you confirm that if you think is true or correct me if is wrong ? Thanks.


If you need to call methods that are specific to ZipOutputStream on your out variable, then its type should not be OutputStream, but ZipOutputStream:

ZipOutputStream out = new JarOutputStream(new FileInputstrem(fileName));
                   ...
out.closeEntry();

This doesn't cause any problem, because since JarOutputStream extends ZipOutputStream, a JarOutputStream is also a ZipOutputStream (and is also an OutputStream, and is also an Object).


Since JarOutputStream extends ZipOutputStream, and since all methods in Java are virtual, doing

((ZipOutputStream) out).closeEntry();

calls the exact same method ass

((JarOutputStream) out).closeEntry();

However, I'd suggest you make the static type a bit more precise:

ZipOutputStream out = new JarOutputStream(new FileInputstrem(fileName));
                   ...
out.closeEntry();


And therefore in my case ((ZipOutputStream)out).closeEntry(); was the same as ((JarOutputStream)out).closeEntry();

That is correct. No reason to write the former whatsoever.


ZipOutputStream.closeEntry();

and

JarOutputStream.closeEntry();

both close the ZIP entry, so you can write another entry into the archive file (if you want to store more than one file into one ZIP/JAR). They do not close the output stream itself. If you want to close your JarOutputStream and the underlying FileOutputStream, use out.close();

Cf.: http://download.oracle.com/javase/1.4.2/docs/api/java/util/zip/ZipOutputStream.html#close() http://download.oracle.com/javase/1.4.2/docs/api/java/util/zip/ZipOutputStream.html#closeEntry()

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜