0

Is there any reason for calling close methods on the StreamWriter class? Why do I have to do it? If I don't close the StreamWriter will I get some kind of undefined behavior?

4
  • streamWriter Which package, where? Commented Jul 1, 2012 at 16:41
  • 2
    @smallB: You're asking about a class which doesn't exist. We must guess that the "streamWriter class" is in fact java.io.OutputStreamWriter (unless you meant some other class). Commented Jul 1, 2012 at 17:12
  • #JBNizet by streamWriter I meant any streamWriter. Commented Jul 1, 2012 at 17:36
  • There is no "streamWriter" superclass or interface. "Any streamWriter" doesn't mean anything. Commented Jul 1, 2012 at 18:35

3 Answers 3

8

Assuming you're talking about java.io.OutputStreamWriter, yes, you should close it, in a finally block, when you don't want to write anything more. This allows the underlying OutputStream to be closed. If the underlying OutputStream is a FileOutputStream, it will release the file descriptor (which is a limited OS resource), and allow other aps to read the file. If it's a SocketOutputSTream, it will signal to the other side that it shouldn't expect anything more from the socket input stream.

In general, streams and readers/writers must always be closed properly. If using Java 7, use the new try-with-resources construct to make sure it's done automatically for you.

Sign up to request clarification or add additional context in comments.

Comments

3

The operating system manages files, and if in java the file is not closed, system wide resources are lost.

In java 7 you can however use

try (OutputStreamWriter outWriter = new OuputStreamWriter(outStream, "UTF-8")) {
   ...
}

without close. (Output streams and writers implement Closeable).

BTW @PriestVallon was just trying to make you formulate your question a bit better/attractive for answering. A "light" response to that can be misunderstood as you've seen.

Comments

1

Writing and reading streams involves quite often the use of os resources,as sockets,file handles and so on.if you're writing on a stream you should also close it,im order to release resources you may have obtained(it depends on the actualresources you are using beneath the stream). Sometimes closing a stream writer involves the release of an exclusive allocation of a resource, or the flushing of temporary data to the stream. Sometimes the close is uneffective, it depends on the kind of stream you have, but the interface must take care of all the cases where a stream have to be closed.

Comments

Your Answer

Draft saved
Draft discarded

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.