This input stream wrapper closes the base input stream when fully read. : InputStream « File Input Output « Java






This input stream wrapper closes the base input stream when fully read.

      
/*
 * Copyright 2004-2011 H2 Group. Multiple-Licensed under the H2 License,
 * Version 1.0, and under the Eclipse Public License, Version 1.0
 * (http://h2database.com/html/license.html).
 * Initial Developer: H2 Group
 */
//package org.h2.util;

import java.io.IOException;
import java.io.InputStream;

/**
 * This input stream wrapper closes the base input stream when fully read.
 */
public class AutoCloseInputStream extends InputStream {

    private final InputStream in;
    private boolean closed;

    /**
     * Create a new input stream.
     *
     * @param in the input stream
     */
    public AutoCloseInputStream(InputStream in) {
        this.in = in;
    }

    private int autoClose(int x) throws IOException {
        if (x < 0) {
            close();
        }
        return x;
    }

    public void close() throws IOException {
        if (!closed) {
            in.close();
            closed = true;
        }
    }

    public int read(byte[] b, int off, int len) throws IOException {
        return closed ? -1 : autoClose(in.read(b, off, len));
    }

    public int read(byte[] b) throws IOException {
        return closed ? -1 : autoClose(in.read(b));
    }

    public int read() throws IOException {
        return closed ? -1 : autoClose(in.read());
    }

}

   
    
    
    
    
    
  








Related examples in the same category

1.Creating an input or output stream on a ByteBuffer
2.Creating a Manifest for a JAR File
3.Convert InputStream to String
4.An limited-data-size input stream
5.An input stream which reads sequentially from multiple sources
6.Combined InputStream
7.Size Limit InputStream
8.Minimal InputStream subclass to fetch bytes form a String
9.Read and return the entire contents of the supplied InputStream. This method always closes the stream when finished reading.
10.Compare two InputStream
11.Read and return the entire contents of the supplied InputStream.
12.Deserializes an object from an input stream.
13.Reads at most certain bytes from input stream and returns them as a byte array.
14.Convert Reader to InputStream
15.A trace of the data that is being retrieved from an input stream
16.EOLConvertingInputStream: InputStream which converts \r bytes not followed by \n and \n not preceded by \r to \r\n.
17.A line reading wrapper that works with byte streams.
18.Smart Encoding InputStream
19.Wraps a stream that has been exported to import the data in readable form
20.LZFInputStream and LZFOutputStream
21.Random input stream