Implementation of Java IO __java

Source: Internet
Author: User
Tags int size wrapper

Look at Javaio from one way:

    Public byte[] Compress (iwritable value) {
        if (value = = null) return null;
        try {
            Bytearrayoutputstream bos = new Bytearrayoutputstream ();
            DataOutputStream out = new DataOutputStream (BOS);
            Value.writefields (out);
            Out.close ();
            return Bos.tobytearray ();
        } catch (Exception e) {
            log.error ("Cannot compress value." + value, e);
            return null;
        }
    }

First Bytearrayoutputstream creates a outputstream, then is dataoutputstream wrapped, then writes the data to DataOutputStream. After writing, the DataOutputStream is closed, but Bytearrayoutputstream can still take the data just written. OutputStream & Bytearrayoutputstream

Here, first look at the Bytearrayoutputstream, it inherits the OutputStream. OutputStream It's worth remembering:

Public abstract class OutputStream
extends Object
implements Closeable, flushable this

abstract class is the Superclass of all classes representing an output stream of bytes. An output stream accepts output bytes and sends them to some sink.

Applications that need to define a subclass of OutputStream must always provide in least a method that writes one byte of Output.

Because it is the father of all output streams. Bytearrayoutputstream, for example, is a byte array (byte-array) output stream from the name, and from the implementation, it can be found that there is a protected byte buf[in it, and this buf byte array is where the byte is really placed. It must also implement Dad's abstract method, write (int), or lose the basic function of writing byte to buf:

    /**
     * Writes the specified byte to this byte array output stream.
     *
     * @param   b The byte to be   written.
     */public
    synchronized void write (int b) {
        ensurecapacity (count + 1);
        Buf[count] = (byte) b;
        Count + 1;
    }
Expansion: FileOutputStream

Another common subclass of OutputStream is FileOutputStream:

public class FileOutputStream
extends outputstream

a file output stream was a output stream for writing data to A File or to a filedescriptor. Whether or not a file was available or may created depends upon the underlying platform. Some platforms, in particular, allow a file to is opened for writing with only one fileoutputstream (or other file-writing o Bject) at a time. In such situations the constructors in this class would fail if the file involved is already open.

FileOutputStream is meant for writing streams of raw bytes such as image data. For writing streams of characters, consider using FileWriter.

Designed to write bytes to files, to write pictures and the like. Where the data resides is the file:

    /**
     * The system dependent file descriptor.
     *
    private final filedescriptor fd;

    /**
     * True If the file is opened for append.
     *
    Private Final Boolean append;

    /**
     * The associated channel, initialized lazily.
     * *
    private filechannel channel;

    /**
     * The path of the referenced file
     * (null if the stream is created with a file descriptor) * *
    Priv ATE final String path;

The true implementation write (int) is related to the system:

    /**
     * Writes the specified byte to this file output stream. Implements
     * The <code>write</code> method of <code>outputstream</code>.
     *
     * @param      b The byte to be   written.
     * @exception  IOException  If an I/O error occurs.
     */Public
    void write (int b) throws IOException {
        write (b, append);
    }

    /**
     * Writes the specified byte to this file output stream.
     *
     * @param   b The byte to be   written.
     * @param   Append   {@code true} if the write operation the
     position to the end of     file
  */
    Private native void write (int b, Boolean append) throws IOException;

Note: OutputStream is related to write Byte, you can refer to another dad: Writer. Filteroutputstream

And then look at DataOutputStream:

public class DataOutputStream
extends Filteroutputstream
implements dataoutput

A data output stream lets A Application Write primitive Java data types to a output stream in a portable way. An application can then with a data input stream to read the data.

Inherits Filteroutputstream and implements the DataOutput interface.

First look at the Filteroutputstream it inherits. This is also a kind of class that we should remember, because he is also a father:

public class Filteroutputstream
extends OutputStream This class are the superclass of all

classes that filter OUTPU T streams. These streams sit in the top of a already existing output stream (the underlying output stream) which it uses as its basic SI NK of data, but possibly transforming the data along the way or providing additional.

The class Filteroutputstream itself simply overrides all methods of OutputStream with versions, all requests to t He underlying output stream. Subclasses of Filteroutputstream may further override some to these methods as as a-provide additional and methods Ds.

It is the father of all the classes that add filters to the output stream. Instead of providing an output stream itself, it wraps an output stream internally:

    /**
     * The underlying output stream to is filtered.
     * *
    protected outputstream out;

This output stream is provided by the class that provides the output stream (the OutputStream subclass), such as the Bytearrayoutputstream described just now.

For this reason, all filteroutputstream subclasses must also have a constructor that passes in an output stream:

    /**
     * Creates an output stream filter built in the top of the specified
     * underlying output stream.
     *
     * @param out of the   underlying output stream to is assigned to
     * The                field <tt>this.out</tt& Gt For later with, or
     *                <code>null</code> If this instance are to being
     *                created without an Underl Ying Stream.
     * * Public
    Filteroutputstream (OutputStream out) {
        this.out = out;
    }

(now, it seems, there is only one constructor.) There is no parameterless constructor because the object is raw for filtering the output stream, and if you don't pass in an output stream, it's filtered by WHO. So that's kind of a coercive measure.

We can also see in the introduction of Filteroutputstream, the original intention of this class is this: Filteroutputstream is simply to achieve the OutputStream method (Implementation of the way is to the bottom of the output stream to achieve ...) It was "simply" achieved ... For example, see how it Implements OutputStream write (int):

    /**
     * Writes the specified <code>byte</code> to this output stream.
     * <p>
     * The <code>write</code> method of <code>FilterOutputStream</code>
     * Calls the <code>write</code> method's its underlying output stream,
     * which is, it performs <tt>out. Write (b) </tt>
     * <p>
     * Implements the abstract <tt>write</tt> method of <tt>outputstream</tt>.
     *
     * @param      b the   <code>byte</code>.
     * @exception  IOException  If an I/O error occurs.
     */Public
    void write (int b) throws IOException {
        out.write (b);
    }

is to have the underlying output stream go to write (int). (out is the output stream of the Filteroutputstream package just described)

And its subclasses are going to do more, and need to provide additional functionality. Now look back on the DataOutputStream. DataOutputStream

From the name point of view, this wrapper class is to write data, look at the class declaration (above), it can write native Java data type (primitive Java) to the output stream. A specific look at the method it contains will know: Write (int)/writeboolean/writebyte/writeint/writelong/writeutf/writedouble and so on, It is true that Java's native type of write methods are implemented (these are implementations of the interface DataOutput). Look at a writeint:

    /**
     * Writes a <code>int</code> to the underlying output stream as four
     * bytes, high byte a. If no exception is thrown, the counter
     * <code>written</code> are incremented by <code>4</code> ;.
     *
     * @param      v   <code>int</code> to is written.
     * @exception  IOException  If an I/O error occurs.
     * @see        java.io.filteroutputstream#out
     *
    /public final void Writeint (int v) throws IOException {
        Out.write ((v >>>) & 0xFF);
        Out.write ((v >>>) & 0xFF);
        Out.write ((v >>>  8) & 0xFF);
        Out.write ((v >>>  0) & 0xFF);
        Inccount (4);
    }

is to write an int type, 4 bytes, a total of 32bits, first write high 8bits (24~31bit), then write 16~23bit, then write 8~15bit, and finally write down 8, 0~7bit. The place to write is the OutputStream object it encapsulates.

So the wrapper class, which inherits the Filteroutputstream, is a new layer of functionality for the simple output flow wrapper. Expansion: Bufferedoutputstream

You can give another example, Bufferedoutputstream:

The public class Bufferedoutputstream
extends Filteroutputstream the

class implements a buffered output stream. By setting up such a output stream, an application can write bytes to the underlying output stream without necessarily CA Using a call to the underlying system for each byte written.

Look at the name, probably used to do the cache. Look at the class introduction, which is designed to cache the output stream so that the underlying call is invoked once every time the output stream is written.

Exactly how to do it. First, it is natural to put a cache first:

    /**
     * The internal buffer where data is stored.
     * *
    protected byte buf[];

    /** * The number of
     valid bytes in the buffer. This value is always
     * in the range <tt>0</tt> through <tt>buf.length</tt>; elements
     * &L T;tt>buf[0]</tt> through <tt>buf[count-1]</tt> contain valid
     * byte data.
     *
    /protected int count;

When initializing Bufferedoutputstream, in addition to specifying the underlying output stream, specify the size of the cache, which defaults to 8192:

    /**
     * Creates a new buffered output stream to write data to the
     * specified underlying output stream.
     *
     * @param out the   underlying output stream.
     * * Public
    Bufferedoutputstream (OutputStream out) {This
        (out, 8192);
    }

    /**
     * Creates a new buffered output stream to write data to the
     * specified underlying output stream with the SP Ecified Buffer
     * size.
     *
     * @param out the    underlying output stream.
     * @param   Size the   buffer size.
     * @exception illegalargumentexception if size &lt;= 0.
     *
    /Public Bufferedoutputstream (outputstream out, int size) {
        super (out);
        if (size <= 0) {
            throw new IllegalArgumentException ("Buffer size <= 0");
        }
        BUF = new Byte[size];
    }

And look at Bufferedoutputstream's write (int):

    /**
     * Writes the specified byte to this buffered output stream.
     *
     * @param      b The byte to be   written.
     * @exception  IOException  If an I/O error occurs.
     */public
    synchronized void write (int b) throws IOException {
        if (count >= buf.length) {
            flushbuffer ();
        }
        buf[count++] = (byte) b;
    }

    /** Flush the internal buffer *
    /private void Flushbuffer () throws IOException {
        if (Count > 0) {
            OUT.WR ITE (buf, 0, Count);
            Count = 0;
        }
    }

Each time is written into the buffer, only after the full of the brush into the output stream, it does reduce the underlying write calls. Conclusion

The above introduction is the Father OutputStream this set of, and write byte correlation. The father of its packing class is Filteroutputstream.

Read Byte can refer to dad InputStream that a set of things, and packaging dad FilterInputStream;

Write character can refer to Dad writer that a set of things, and packaging class dad Filterwriter;

read the characters can refer to Dad reader that set of things, and packaging class dad FilterReader.

Actually remember a few dads, the relationship is clear.

Here also involves a good design pattern: Decorator mode, interested to understand. DataOutput

Finally, dataoutput this interface:

Public interface DataOutput The

DataOutput interface provides for converting data from any of the Java primitive To a series of bytes and writing the bytes to a binary stream. There is also a facility to converting a String into modified UTF-8 format and writing the resulting series of bytes.
  
   for all of the methods in this interface that write bytes and it is generally true so if a byte cannot be written to any Rea Son, an IOException is thrown.
  

It provides an interface for converting Java native types to bytes.

But you can only turn to Java native types, you want to go to custom/complex objects need to implement something, such as the implementation of writable.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.