C # Learn from the story: Stream (II)

Source: Internet
Author: User
Tags ftp file

Previous: http://www.bkjia.com/kf/201203/123535.html

TextReader and StreamReader
Directory:
Why do you want to introduce TextReader?
Common attributes and methods of TextReader
TextReader example
Think of polymorphism from StreamReader
Brief Introduction to Encoding
Definition and function of StreamReader
Common method attributes of the StreamReader class
StreamReader example
Summary
 
 
 
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: virtual string ReadLine () method:
As the name suggests, this method reads data from each row and returns the character strings of the current row.
* 9: virtual string 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 is: {0}", allData );
Reader. Close ();
}

Console. ReadLine ();

Output result:

 


 

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 classic example of polymorphism. You may wish to deeply understand this important concept.

 

Brief Introduction to 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 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 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 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 FileStream.
Sr. BaseStream. Seek (0, SeekOrigin. Begin );
 

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 (txtFilePath ))
{
// Use Encoding. ASCII to try
Using (StreamReader reader = new StreamReader (stream, Encoding. ASCII, false ))
{
// StreamReader. ReadBlock () method
DisplayResultStringByUsingReadBlock (reader );
}
}

// Try to use the file location to get StreamReader directly. By the way, use Encoding. Default
Using (StreamReader reader = new StreamReader (txtFilePath, Encoding. Default, false, 123 ))
{
// StreamReader. ReadLine () method
DisplayResultStringByUsingReadLine (reader );
}

// You can also use the File. OpenText method to directly obtain the StreamReader object.
Using (StreamReader reader = File. OpenText (txtFilePath ))
{
// StreamReader. ReadLine () method
DisplayResultStringByUsingReadLine (reader );
}

Console. ReadLine ();
}

/// <Summary>
/// Use StreamReader. Read ()
/// </Summary>
/// <Param name = "reader"> </param>
Public static void DisplayResultStringByUsingRead (StreamReader reader)
{
Int readChar = 0;
String result = string. 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 ()
/// </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 the StreamReader. ReadBlock () method to get the first 10 data in the Text file: {0}", result );
}

/// <Summary>
/// Use StreamReader. ReadLine ()
/// </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 the StreamReader. Read () method to obtain the data of row {1} in the Text file: {0}", resultString, I );
I ++;
}

}

Output result:

 


 

Summary

This chapter introduces the definition concepts and precautions of TextReader and StreamReader in detail. I hope you can learn more about TextWriter and StreamWriter in this article.

Coming soon!

 

From anti-clockwise alert

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.