
com.gc.iotools.stream.writer.CloseOnceWriter Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of easystream Show documentation
Show all versions of easystream Show documentation
EasyStream is a small set of utilities for dealing with
streams (InputStreams
and OutputStreams).
The aim is to ease the use of
pipes when they're required.
Main features are:
* "Convert" an
OutputStream to an InputStream.
* Count the number of bytes read or
wrote to a given stream.
* While reading the data from an InputStream
copy it to a supplied
OutputStream.
* Read the content of an InputStream
multiple times or seek to a
definite position
The newest version!
package com.gc.iotools.stream.writer;
/*
* Copyright (c) 2008, 2015 Gabriele Contini. This source code is released
* under the BSD License.
*/
import java.io.FilterWriter;
import java.io.IOException;
import java.io.Writer;
/**
*
* A CloseOnceWriter
wraps some other Writer
* preventing multiple invocations of the method {@link #close()}.
*
*
* It forwards all requests to the contained writer, except the
* {@linkplain #close()} method that is passed only one time to the underlying
* stream.
*
*
* This is useful with some non conforming Writer
that don't allow
* close()
to be called multiple times.
*
*
* @see java.io.Writer#close()
* @author Gabriele Contini
* @since 1.2.14
* @param
* Type of the Writer passed in the constructor.
* @version $Id: CloseOnceWriter.java 527 2014-02-24 19:29:50Z
* $
*/
public class CloseOnceWriter extends FilterWriter {
private int closeCount = 0;
/**
* Construct a CloseOnceWriter
that forwards the calls to the
* source Writer passed in the constructor.
*
* @param source
* original Writer
*/
public CloseOnceWriter(final T source) {
super(source);
if (source == null) {
throw new IllegalArgumentException("Source Writer can't be null");
}
}
/**
* {@inheritDoc}
*
*
* Multiple invocation of this method will result in only one invocation of
* the close()
on the underlying stream.
*
*/
@Override
public void close() throws IOException {
synchronized (this) {
this.closeCount++;
if (this.closeCount > 1) {
return;
}
}
this.out.close();
}
/**
* Returns the number of time that close was called.
*
* @return Number of times that close was called
*/
public int getCloseCount() {
return this.closeCount;
}
/**
*
* Returns the wrapped (original) Writer
passed in the
* constructor.
*
*
* @return The original Writer
passed in the constructor
*/
public T getWrappedWriter() {
@SuppressWarnings("unchecked")
final T result = (T) super.out;
return result;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy