The following example shows how to use the bufferedinputstream class to read text files.
First, you need to declare a byte array as the buffer, and then cyclically read the text content into the buffer, convert the buffer into a string, and print it to the console.
/**
*
* @ Author outofmemory.cn
*/
Public class main {
/**
* Read text from a file
*/
Public void readfromfile (string filename ){
Bufferedinputstream bufferedinput = NULL;
Byte [] buffer = new byte [1024];
Try {
// Create a bufferedinputstream object
Bufferedinput = new bufferedinputstream (New fileinputstream (filename ));
Int bytesread = 0;
// Read the content in bytes from the file.-1 is returned when the read method ends at the end of the file.
While (bytesread = bufferedinput. Read (buffer ))! =-1 ){
// Convert the read bytes into string objects
String chunk = new string (buffer, 0, bytesread );
System. Out. Print (chunk );
}
} Catch (filenotfoundexception ex ){
Ex. printstacktrace ();
} Catch (ioexception ex ){
Ex. printstacktrace ();
} Finally {
// Disable bufferedinputstream
Try {
If (bufferedinput! = NULL)
Bufferedinput. Close ();
} Catch (ioexception ex ){
Ex. printstacktrace ();
}
}
}
/**
* @ Param ARGs command line parameters
*/
Public static void main (string [] ARGs ){
New Main (). readfromfile ("myfile.txt ");
}
}
How does bufferedinputstream read files?