Byte Input/Output streams

Byte I/O streams provide sequential input or output of bytes. A stream can represent many different kinds of sources and destinations, including disk files, devices, other programs, and memory arrays.

The InputStream is root class for input streams. Main methods are read(), that allow to read one or more bytes from stream. When data are finished in stream, these methods return -1.

The OutputStream is root class for output streams. Main methods are write(), that allow to write one or more bytes to the stream.

You must close streams after using directly or use try-with-resource statement.

static void copyData(InputStream is, 
    OutputStream os, int buffsize) throws IOException {
    byte[] buff = new byte[buffsize <= 0 ? 1024 : buffsize];
    int cnt = is.read(buff);

    while (cnt > 0) {
        os.write(buff);
        cnt = is.read(buff);
    }

    os.flush();
}

static void copyFiles(File srcFile, File dstFile) {

    try (InputStream src = new BufferedInputStream(new FileInputStream(srcFile));
         OutputStream dst = new BufferedOutputStream(new FileOutputStream(dstFile))
        ) {
        copyData(src, dst, 1024);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

byte I/O streams overview

class description
InputStream Root class of all classes representing an input stream of bytes.
OutputStream Root class of all classes representing an output stream of bytes.
FileInputStream Input stream that obtains bytes from a file in a file system.
FileOutputStream Output stream that writes bytes to a file in a file system.
ByteArrayInputStream Input stream that obtains bytes from a buffer of bytes.
ByteArrayOutputStream Output stream that writes bytes into a byte array. The buffer automatically grows as data is written to it. The data can be retrieved using toByteArray() and toString().
BufferedInputStream Wraps another input stream to support the mark and reset methods. This is also useful when working with slow input streams such as FileInputStream.
BufferedOutputStream Wraps another output stream to cache data before actually writing to the stream. This is useful when working with slow output streams such as FileOutputStream.