[C #] Learn from the story: stream (II)

Source: Internet
Author: User
Tags ftp file

 

From: http://www.cnblogs.com/JimmyZheng/archive/2012/03/19/2405216.html

Textreader and streamreader

Why do you want to introduce textreader?

First, let's understand what textreader is. If we start with the literal meaning, we will suddenly realize it.

How can I read a text reader? Smart, you will surely think, of course, through continuous

Before introducing streamreader, why do we need to read this stuff? The answer is actually very simple: they

The two are parent-child relationships. To learn about streamreader, it is best to know his father first. Please allow me to give a brief introduction to them:

 

Common attributes and methods of textreader:

We can close our eyes and imagine the scope of the word text. It contains many file types. We can use it on notepad.

Use any language (English, Chinese, C #, tianshu, JavaScript, jquery, XML, XAML, SQL, C ++ ......), So many

The language text is ultimately composed of char, So Microsoft constructed the abstract class textreader

A series of operations to read text. We cannot directly instantiate textreader. It should be an abstract class, only

Defines the behavior of a class, not specific to the specific implementation. Well, let's see what classes the textreader defines:

1: Has a protected Type constructor

* 2:
Void close () method: Like the previous stream, textreader also has the close method, which must be kept in mind,

Disable it after use.

* 3:
Void dispose () method: release all resources held by the textreader (Note: if the textreader holds stream or other resources

Object. When the textreader executes the dispose method, the stream object is also recycled)

* 4: int PEEK () method

This method is mainly used to find the next char of the current char. When the returned value is-1, it indicates that the next char is the char at the last position.

* 5: int read () method:

Similarly, the read () method reads the next char, but unlike the peek method, the read () method directs the pointer to the next character, but the peek

It still points to the original character

* 6: int read (char [] buffer, int index, int count) method:

This overload read method is a bit similar to the read method of stream in the previous chapter. The difference is that a parameter is a byte array, and this is a char array,

(Note: Data is read into the buffer array through reader), index: from which position, Count: Number of char reads

* 7:
Int readblock (char [] buffer, int index, int count) method:

It is basically the same as the read method. The difference is that readblock is more efficient, and readblock is NOT thread-safe.

* 8: virtualstring Readline () method:

As the name suggests, this method reads data from each row and returns the character strings of the current row.

* 9: virtualstring readtoend () method:

String containing all characters from the current position to the end of textreader

 

The following example shows how to update the above method:

String text = "ABC \ nabc"; using (textreader reader = new stringreader (text) {While (reader. Peek ()! =-1) {console. writeline ("Peek = {0}", (char) reader. peek (); console. writeline ("read = {0}", (char) reader. read ();} reader. close ();} using (textreader reader = new stringreader (text) {char [] charbuffer = new char [3]; int DATA = reader. readblock (charbuffer, 0, 3); For (INT I = 0; I <charbuffer. length; I ++) {console. writeline ("data read through readblock: {0}", charbuffer [I]);} reader. close ();} using (textreader reader = new stringreader (text) {string linedata = reader. readline (); console. writeline ("the first row of data is: {0}", linedata); reader. close ();} using (textreader reader = new stringreader (text) {string alldata = reader. readtoend (); console. writeline ("all data: {0}", alldata); reader. close ();} console. readline ();

 

 

Streamreader debut

At last, today's leading role debuted. After so much preparation, you will get twice the result with half the effort.

 

Think of polymorphism from streamreader

One more thing to mention before streamreader is explained is polymorphism. What is the concept of polymorphism? Smart, you will surely think of polymorphism, not just the species of sub-classes.

Form? Yes, but this is not completely true. In the real world, my father helped his son buy a house, but he did not write his son's name on the real estate license,

Therefore, this House can be used by the son and his father. The son can decorate the house according to his hobbies, and the father can also live in the house decorated by the son. That is to say, the father can

Flexible use of the subclass function, more scientific is that the subclass pointer allows (assigned to) the parent class pointer. In the preceding example

TextReader reader = new StringReader(text)

This is a typical example of polymorphism. You may wish to deeply understand this important concept.

 

Brief Introduction to encoding Encoding

Why do we need to briefly introduce encoding? Because encoding plays a very important role in stream and related classes,

As the encoding class will be explained in detail in subsequent sections, I will introduce some important encoding of the encoding class first.

 

These are some specific encodings In the encoding class. You can understand them first, but you must note that when using default, if you use a machine with different encodings,

Pay attention to the encoding rules of the server or other operating systems. For example, if you perform encoding in a Chinese operating system but publish the code to another language

In the system, a problem occurs. At this time, You must select a general encoding.

Definition and function of streamreader class

Definition of streamreader: implements a textreader to read characters from the byte stream with a specific encoding.

In stream operations, streamreader is very important for stream reading. Why? We often use file copying, moving, uploading, downloading, compressing, and saving,

Remote FTP file reading, even httpresponse, can be easily processed by streamreader of any derived class related to the stream. Of course, you can even customize

Related Derived classes to implement complex serialization. In actual projects, we may have encountered many of the above situations, and sometimes the garbled problem will drive us crazy, but as long as we have a deep understanding of the basics,

I believe everyone can find a solution suitable for themselves.

Common attributes and methods of streamreader class

In fact, some methods of streamreader have already been carefully described in its parent class textreader, but I personally think constructors and attributes are the key points.

First, the constructor:

* 1: streamreader (Stream)

Put stream as a parameter into streamreader. In this way, streamreader can read the stream, and stream objects can be very extensive, including the derived class objects of all streams.

* 2: streamreader (string, encoding)

Here, the string object is not a simple string but the address of the specific file, and then reads the data in the stream based on the user's selection of encoding.

* 3: streamreader (string, bool detectencodingfrombyteordermarks)

Sometimes we want the program to automatically determine the encoding used to read data. In this case, the detectencodingfrombyteordermarks parameter will take effect. When it is set to true, the first three bytes of the stream can be viewed.

To detect the encoding. If the file starts with an appropriate byte order marker, this parameter automatically recognizes UTF-8, little-Endian Unicode, and big-Endian Unicode text, and when it is false, the method goes with the user supplied

Encoding

* 4: streamreader (string, encoding, bool detectencodingfrombyteordermarks, int
Buffersize)

This release provides reloads of four parameters. We have learned about the first three, and the last is the buffer size setting,

* Streamreader also has some other constructor functions, all of which are extensions of the above four. Therefore, this example uses the above four constructor to describe them.

Attribute:

1: basestream

Everyone should have no problem with stream operations in the previous chapter. I just cut down the topic. The simplest understanding is to re-extract the stream object of the above constructor for a series of operations,

But what if the constructor is a path? Similarly, the constructor can convert the path file into a stream object.

FileStream fs = new FileStream ( "D:\\TextReader.txt", FileMode.Open , FileAccess.Read ) ; StreamReader sr= new StreamReader ( fs ) ; 
// In this example, basestream is filestreamsr. basestream. Seek (0, seekorigin. Begin );
 
Copy code

2: currentencoding:

Obtains the encoding of the current streamreader.

3: endofstream:

Judge whether streamreader is at the end of the current stream

 

 

Finally, streamreader is used as an example of filestream.

Static void main (string [] ARGs) {// file address string txtfilepath = "D: \ textreader.txt "; // define the char array char [] charbuffer2 = new char [3]; // use the filestream class to convert the file text data into a stream and then put it into the streamreader constructor using (filestream stream = file. openread (txtfilepath) {using (streamreader reader = new streamreader (Stream) {// streamreader. read () method displayresultstringbyusingread (Reader) ;}} using (filestream stream = file. openread (txtfi Lepath) {// use encoding. ASCII to try using (streamreader reader = new streamreader (stream, encoding. ASCII, false) {// streamreader. readblock () method displayresultstringbyusingreadblock (Reader) ;}// you can use the file location to directly obtain streamreader. By the way, encoding is used. default using (streamreader reader = new streamreader (txtfilepath, encoding. default, false, 123) {// streamreader. readline () method displayresultstringbyusingreadline (Reader );} // You can also use file. the opentext method directly obtains the streamreader object using (streamreader reader = file. opentext (txtfilepath) {// streamreader. readline () method displayresultstringbyusingreadline (Reader);} console. readline () ;}/// <summary> // use streamreader. read () method // </Summary> // <Param name = "Reader"> </param> Public static void displayresultstringbyusingread (streamreader reader) {int readchar = 0; string result = stri Ng. Empty; while (readchar = reader. Read ())! =-1) {result + = (char) readchar;} console. writeline ("use streamreader. read () method to get the data in the text file: {0} ", result) ;}/// <summary> /// use streamreader. readblock () method // </Summary> // <Param name = "Reader"> </param> Public static void displayresultstringbyusingreadblock (streamreader reader) {char [] charbuffer = new char [10]; string result = string. empty; reader. readblock (charbuffer, 0, 10); For (INT I = 0; I <Charbuffer. length; I ++) {result + = charbuffer [I];} console. writeline ("use streamreader. the first 10 data records in the text file are {0} ", result) ;}/// <summary> /// use streamreader. readline () method // </Summary> // <Param name = "Reader"> </param> Public static void displayresultstringbyusingreadline (streamreader reader) {int I = 1; string resultstring = string. empty; while (resultstring = reader. readline ())! = NULL) {console. writeline ("use streamreader. the data in row {1} in the text file is: {0} ", resultstring, I); I ++ ;}} obtained by the read () method ;}}

Output result:

 

Related Article

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.