Skip to content

Tag: outputstream

Proper way to close an AutoCloseable

What is the most reliable pattern to follow when closing an OutputStream, ServerSocket, or other object that implements the AutoCloseable interface? Should I use try-catch-finally? Or a shutdown hook. Answer The correct way to use an AutoCloseable instance is with a try-with-resources block, so the resource i…

writing to OutputStream having capacity restriction

Following the question I asked before: I am implementing an ByteArrayOutputStream having capacity restriction. My main limitation is an amount of available memory. So having such stream os: When I write more than say 1MB to the output stream I need to “stop”. I prefer not throw exception but write…

Write a binary downloaded file to disk in Java

I have a software that allow to write add-on in javascript files (.js) that allow to use Java function (I don’t know if this is common, I never saw java call in javascript file before) I need to download a binary file from a webserver and write it to the hard drive. I tried the following code: The resul…

Is there a Null OutputStream in Java?

I need to specify an OutputStream for an API I’m using, but I don’t actually have a need for the output. Does Java have an OutputStream equivalent to > /dev/null? Answer Since Java 11, there is a static utility that does exactly what you need, a static factory method OutputStream.nullOutputStre…