Copy Stream with buffer in Java

Description

The following code shows how to copy Stream with buffer.

Example


//from www .j a  va 2s.  c o  m
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class Main {

  public static void main(String[] args) {

    try {
      copy(System.in, System.out);
    } catch (IOException ex) {
      System.err.println(ex);
    }
  }

  public static void copy(InputStream in, OutputStream out) throws IOException {

    BufferedInputStream bin = new BufferedInputStream(in);
    BufferedOutputStream bout = new BufferedOutputStream(out);

    while (true) {
      int datum = bin.read();
      if (datum == -1)
        break;
      bout.write(datum);
    }
    bout.flush();
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    I/O »




Binary File
Byte Array
CharSet
Checksum
Console
Create Copy Move Delete
Directory
Drive
Encode Decode
File Attribute
File Lock
File System
GZIP
Jar File
NIO Buffer
Path
Scanner
StreamTokenizer
Temporary File
Text File
Zip