How does bufferedinputstream read files?

Source: Internet
Author: User

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?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.