Analysis of the streamreader class and its methods Readline, read, and readtoend
Source: Internet
Author: User
First, the structured parameters of the streamreader class are rich. Here, I think the most common ones are streamreader (Stream stream) and streamreader (string Str ). The first one can be directly put into a data stream, such as filestream, while the second one can be simply put into STR, such as "C:/test.txt" It focuses on the use of its three methods. 1. Readline () When \ n \ r or \ r \ n is encountered, this method returns the previous string, and the internal pointer moves back one bit to start reading from the new place next time. Knowing that null is returned at the end of the data So this is often used String content; Try { Streamreader sr = new streamreader ("test.txt "); Content = Sr. Readline (); While (null! = Content) { Debug. writeline (content ); Content = Sr. Readline (); } Sr. Close (); } Catch (ioexception E) { Debug. writeline (E. tostring ()); } 2. Read () This method reads a character each time, and returns a positive number representing the character. when the end of the unique file is-1. Modify the preceding usage: Try { Streamreader sr = new streamreader ("test.txt "); Int content = Sr. Read (); While (-1! = Content) { Debug. Write (convert. tochar (content )); Content = Sr. Read (); } Sr. Close (); } Catch (ioexception E) { Debug. writeline (E. tostring ()); } Here, we need to add a bit. Read () also has a usage method Int read (char [] buffer, int index, int count ); Read from the index position of the file stream, to the Count characters, store them in the buffer, and return a positive number. The internal pointer is removed by one digit, ensure that the next read starts from the new location. For example: Try { Streamreader sr = new streamreader ("test.txt "); Char [] buffer = new char [128]; Int Index = Sr. Read (buffer, 0,128 ); While (index> 0) { String content = new string (buffer, 0,128 ); Debug. Write (content ); Index = Sr. Read (buffer, 0,128 ); } Sr. Close (); } Catch (ioexception E) { Debug. writeline (E. tostring ()); } 3. readtoend () This method is suitable for reading small files and returning the entire file at one time. The preceding modification is as follows: Try { Streamreader sr = new streamreader ("test.txt "); String content = Sr. readtoend (); Debug. writeline (); Sr. Close (); } Catch (ioexception E) { Debug. writeline (E. tostring ()); }
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.