BufferedInputStream class
java.lang.Object
|
+-java.io.InputStream
|
+-java.io.FilterInputStream
|
+-java.io.BufferedInputStream
Java's BufferedInputStream class allows you to "wrap" any InputStream into a buffered stream and achieve this performance improvement.
BufferedInputStream has two constructors:
BufferedInputStream(InputStream inputStream) creates a buffered stream using a default buffer size. BufferedInputStream(InputStream inputStream, int bufSize) the size of the buffer is passed in bufSize.
A BufferedInputStream adds the ability to buffer the input and to support the mark and reset methods.
When the BufferedInputStream is created, an internal buffer array is created.
Constructor
BufferedInputStream(InputStream in)
- Creates a BufferedInputStream and saves its argument, the input stream in, for later use.
BufferedInputStream(InputStream in, int size)
- Creates a BufferedInputStream with the specified buffer size, and saves its argument, the input stream in, for later use.
int available()
- Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.
void close()
- Closes this input stream and releases any system resources associated with the stream.
void mark(int readlimit)
- See the general contract of the mark method of InputStream.
boolean markSupported()
- Tests if this input stream supports the mark and reset methods.
int read()
- See the general contract of the read method of InputStream.
int read(byte[] b, int off, int len)
- Reads bytes from this byte-input stream into the specified byte array, starting at the given offset.
void reset()
- See the general contract of the reset method of InputStream.
long skip(long n)
- See the general contract of the skip method of InputStream.
Revised from Open JDK source code
Create BufferedInputStream from FileInputStream
import java.io.BufferedInputStream;
import java.io.FileInputStream;
public class Main {
public static void main(String args[]) throws Exception {
FileInputStream fis = new FileInputStream("c:/a.htm");
BufferedInputStream bis = new BufferedInputStream(fis);
int i;
while ((i = bis.read()) != -1) {
System.out.println(i);
}
fis.close();
}
}
Read byte array out of BufferedInputStream
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
public class Main {
public static void main(String[] args) throws Exception {
File file = new File("C:/ReadFile.txt");
FileInputStream fin = new FileInputStream(file);
BufferedInputStream bin = new BufferedInputStream(fin);
byte[] contents = new byte[1024];
int bytesRead = 0;
String strFileContents;
while ((bytesRead = bin.read(contents)) != -1) {
strFileContents = new String(contents, 0, bytesRead);
System.out.print(strFileContents);
}
bin.close();
}
}