How should I check if BufferedWriter is already closed?

青春壹個敷衍的年華 提交于 2019-12-05 16:57:39

Calling close method on already closed Writer has no impact.

Still, if you want to know if the Writer is closed, you can call writer.flush(), if it throws IOException then it means the Writer is already closed.

For your second question, closing a stream doesn't nullify the reference. You have to explicitly set it to null.

you can check if bufferredWriter not equal to null

if(bufferredWriter!=null)
{
bufferredWriter.close();
}

If you are using java7 or more then you need not to worry about closing the BufferredWriter

JDK 7 onwards you can make you of try with resource

for example

try(BufferredWriter bufferedWriter=new BufferredWriter())
{

//your code
}
catch(Exception e)
{
}
    BufferedWriter vf = new BufferedWriter(new FileWriter("file"));

    if (vf != null)
    {
        vf.close();
        vf.close(); //won't cause any problem
    }

you can close BufferedWriter as many times as you want if it is not null. So no need to check specifically if BufferedWriter is open or not.

Even better if you surround close statement in try/catch in case IOException occurs.

From javadocs

Closes the stream, flushing it first. Once the stream has been closed, further write() or flush() invocations will cause an IOException to be thrown. Closing a previously closed stream has no effect.

And as explained by sidgate, closing a stream won't nullify the reference you have to assign it manually.

bufferedWriter.close() - Closes this writer. The contents of the buffer are flushed, the target writer is closed, and the buffer is released. Only the first invocation of close has any effect.

Refer this

Also, you can check like this

Define below 2 variables as instance variable

BufferedWriter bufferWriter;
boolean isOpen = false;

Then,

try {
    if (!isOpen) {
        bufferWriter = new BufferedWriter(new FileWriter(file, true));
        bufferWriter.write(initialData);
        isOpen = true;
    }
    bufferWriter.write(remainingData);
    bufferWriter.flush();
    Log.d(TAG, "written to file:" + file.getAbsolutePath());
} catch (IOException e) {
    Log.v("IOException", e.toString());
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!