BufferedInputStream
In this chapter you will learn:
- How to use Java BufferedInputStream to make the reading faster
- How to create BufferedInputStream from FileInputStream
- How to read byte array out of BufferedInputStream
Use BufferedInputStream
java.lang.Object/*from ja v a2 s .c o m*/
|
+-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.
Create BufferedInputStream from FileInputStream
The following code creates BufferedInputStream
from
FileInputStream
.
import java.io.BufferedInputStream;
import java.io.FileInputStream;
//j a v a 2 s . co m
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
Once we have an BufferedInputStream
we can use it as any stream classes to
read byte array out of BufferedInputStream
.
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
/*jav a 2 s . c o m*/
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();
}
}
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » Reader Writer