Text I/O using Reader and Writer
TextWriter
Category and TextReader
class is an abstract class-based text, an important subclass thereof comprising: StreamWriter
, , StreamReader
stream processing operation; StringWriter
, StringReader
processing operation of the string. Note: For C programmers, it is StreamWriter
similar to printf()
or fprintf()
, and StringWriter
similar sprintf()
.
1.TextWriter
TextWriter
Is an abstract base class, it contains the following subclasses:
- ① Used to write HTML for the browser client
HtmlTextWriter
- ② Used to write text to the HTTP response object in the ASP.NET web page
HttpWriter
- ③ Use the indentation control to write text
IndentedTextWriter
- ④ Write characters to the stream
StringWriter
- ⑤ Write characters to the string
StringWriter
TextWriter
There are 3 attributes:, Encoding
used to return the character encoding of the output FormatProvider
;, used to refer to the object formatting the text NewLine
;, used to return the line ending character used on the current platform.
Methods in the TextWriter class:
Close
, Close TextWriter and release all related resourcesDispose
, Release resources related to TextWriterFlush
, To write the unregistered data kept in the TextWriter bufferSynchronized
, A thread-safe package for creating TextWriter objectsWrite
, Write data to the streamWriteLine
, Write data to the stream and wrap
The Write()
method of TextWriter is to write data out as a string. It should be noted that compared with other classes: Stream
the Write()
method of writing is bytes, BinaryWriter
the Writer()
method is to write the basic data types in a primitive way.
Write()
The method can object
write out the object, and it will call the object's ToString()
method to convert it into a string. You can also bring a format string. The usage of the format string is Console.Write()
similar Console.Write()
to TextWriter
the method. In fact, the method calls the same method.
The static Synchronized()
method can TextWriter
create a thread-safe wrapper to ensure its safety, so that TextWriter
two threads using the same one will not interfere with each other.
2.StreamWriter
StreamWriter is a subclass of TextWriter, which is used to write characters into the stream through a specific encoding method. The default encoding method is UTF-8
that this method is suitable for the characters of the uniform encoding standard on the local version of the operating system. If you want to use other encoding methods, you can use System.Text
the ASCII and UTF-7 encoding provided by the namespace, or System.Text.Encoding
create your own encoding method.
When constructing a StreamWriter object, you can specify a file name or the name of an existing stream, and specify an encoding method. The following code snippet shows how to create a StreamWriter object that writes content to a file:
FileStream fs = new FileStream(@"C:\temp\foo.txt", FileMode.Create);
StreamWriter writer = new StreamWriter(fs);
Among them, the FileStream object is used to write content to the foo.txt file, and the function of the StreamWriter object is to convert characters into bytes and then output to FileStream
it.
StreamWriter
There is a AutoFlush
property, when the property is true, the Write()
buffer will be refreshed once the object beauty performs an operation. This ensures that the output content is always up-to-date, but this approach is not StreamWriter
as effective as allowing its output content to be buffered. BaseStream
Properties provide access to the basic Stream object.
Apart from the TextWriter
addition to the methods inherited, the StreamWriter
class does not add any new method, but a heavy load, and for writing character string to the flow Write()
method.
3.StringWriter method
StringWriter
Used to write its output content into a string. Since the written character string is in a modified state, the output content is actually written StringBuilder
, not written to String
, because String
it cannot be changed.
StringWriter has a set of Write()
methods, GetStringBuiler()
and ToString()
methods, used to deal with the buffer in the creation of strings.
The following code shows how to create and use StringWriter
:
StringWriter sw = new StringWriter();
int n = 42;
sw.Write("The value of n is {0}", n);
sw.Write("... and some more characters");
Console.WriteLine(sw.ToString());
4.TextReader
TextReader
The class is used to read strings. TextReader
The class has two subclasses StreamReader
and StringReader
. This class contains TextWriter
fewer methods than the class, but the processing method is the same:
Close
, Close TextReader and release all related resourcesPeek
, Browse the next character, but don’t remove it from the input streamRead
, Read the characters into the character arrayReadBlock
, Continue to read characters into a character array or block until enough characters are read or the end of the file is reachedReadLine
, Read in a line of characters and return it as a stringReadToEnd
, Has been read to the end of the stream, and all characters are returned as a stringSynchronized
, Create a thread-safe package of TextReader
5.StreamReader
StreamReader
The class supports character-oriented input in streams, so this class can be used to read text line by line from a file. StreamReader
Any selected character encoding can be used, but UTF-8 is used by default, because this encoding can handle characters under the unified encoding standard.
When creating StreamReader
, there are 10 optional constructors to create objects in different ways according to the following parameters in different situations:
- ① According to the file name, the character encoding method may not be specified
- ② According to the
Stream
reference, it is also possible not to specify the encoding method
The StreamReader class has two attributes:, BaseStream
used to return a reference to the Stream contained in the class CurrentEncoding
;, used to return the character encoding used by the current reader object.
StreamReader
There are several different ways to read data in it. ReadLine()
The method is used to read a row of data and return it as a string. ReadToEnd()
The method is used to read the entire stream, and it is also returned as a string. There are also two Read()
methods, one is used to return the next character in the stream (if the end of the stream has been reached, then return -1
), the other is used to read the specified number of characters into the next character array . In addition, you can Peek()
browse the next character in the stream without removing it from the stream.
6.StringReader
Use StringReader to read characters from a string, and you can read one, multiple, or a whole line of characters at a time. This class is useful if you need to treat strings as text files.
7. Application examples
Read in each C# file, remove the comment in each line, add the line number, and write to another file:
using System;
using System.IO;
using System.Text;
namespace ConsoleApp18流_文件IO
{
class CopyFileAddLineNumber
{
public static void MMain(string[] args) {
string infname = @"E:\Visual Studio 2019\C#\Mooc学习\ConsoleApp18流、文件IO\CopyFileAddLineNumber.cs";
string outfname = "CopyFileAddLineNumber.txt";
if (args.Length >= 1) infname = args[0];
if (args.Length >= 2) outfname = args[1];
try {
FileStream fin = new FileStream(infname, FileMode.Open, FileAccess.Read);
FileStream fout = new FileStream(outfname, FileMode.Create, FileAccess.Write);
StreamReader brin = new StreamReader(fin, Encoding.Default);
StreamWriter brout = new StreamWriter(fout, Encoding.Default);
int cnt = 0; // 行号
string s = brin.ReadLine();
while (s != null) {
cnt++;
s = deleteComments(s); // 去掉以 // 开始的注释
brout.WriteLine(cnt + ":\t" + s); // 写入
Console.WriteLine(cnt + ":\t" + s); // 在控制上显示
s = brin.ReadLine(); // 读入
}
brin.Close(); // 关闭缓冲读入流及文件读入流的连接
brout.Close();
} catch (FileNotFoundException) {
Console.WriteLine("File not found!");
} catch (Exception e2) {
Console.WriteLine(e2);
}
}
private static string deleteComments(string s) {
// 去掉以 // 开始的注释
if (s == null) return s;
int pos = s.IndexOf("//");
if (pos < 0) return s;
return s.Substring(0, pos);
}
}
}
operation result:
Use File's text file function
The processing of text files is more commonly used, so .NET Framework
a special File class is provided to handle the related functions of text files. File is a static class, and File.方法
you can use " " directly .
Among these methods, one type is to get a stream for easy operation, such as File.OpenText(path)
or File.AppendText(path)
get a UTF-8 code StreamWriter
, and File.OpenText(path)
get a UTF-8 code StreamReader
.
The other type is more convenient. There is only one way to open, read and write, and close files, including:
File.ReadAllText(path, encoding)
Read all the text of a fileFile.ReadAllLines(path, encoding)
Read an array of all lines of a fileFile.WriteAllText(path, text, encoding)
Write text to a fileFile.WriteAllLines(path, lines, encoding)
Write the text array to a fileFile.AppendAllText(path, text, encoding)
Append text to a fileFIle.AppendAllLines(path, lines, encoding)
Append text array to a file
In addition, there is a File.ReadAllBytes(path) that can read all the bytes of any file at one time.
For example, FileReadWrieText() uses the File class to read and write files:
public static void FileReadwriteText() {
string path = @"E:\Visual Studio 2019\C#\Mooc学习\ConsoleApp18流、文件IO\bin\Debug\FileText.txt";
// 创建文件(UTF-8编码)
if (!File.Exists(path)) {
using (StreamWriter sw = File.CreateText(path)) {
sw.WriteLine("Hello");
sw.WriteLine("And");
sw.WriteLine("Welcome");
}
}
// 读文件(UTF-8编码)
using (StreamReader sr = File.OpenText(path)) {
string s = "";
while ((s = sr.ReadLine()) != null) {
Console.WriteLine(s);
}
}
}
For example, FileReadWriteAlLines uses the File class to read and write text files at once.
public static void FileReadwriteAllLines() {
string path = @"E:\Visual Studio 2019\C#\Mooc学习\ConsoleApp18流、文件IO\bin\Debug\FileText1.txt";
Encoding encoding = Encoding.Default;
// 一次性写入文件内容
File.WriteAllText(path, "hello\nworld\n", encoding);
// 一次性追加文件内容
File.AppendAllLines(path, new string[] {
"good", "file" }, encoding);
// 一次性读文件内容
string[] lines = File.ReadAllLines(path, encoding);
foreach (string s in lines)
Console.WriteLine(s);
}
Standard input/output
Computer systems have default standard input devices and output devices. For a general system, the standard input is usually a keyboard, and the standard output is usually a monitor screen. The C# program uses the character interface to communicate with the standard input/output of the system, that is, reading in data from the keyboard or outputting data to the screen is a very common operation.
In C # may be used Console
to handle the Operations Console. Console has three static
attributes: Console.In
, , Console.Out
, Console.Error
respectively, in the system standard input, standard output and standard error associated.
Console.In
Is TextReader
the object of the class, Console.Out
and Console.Error
is TextWriter
the object of the class. You can use them to perform a variety of read and write operations.
In Console.Read()
fact, Console.ReadLine()
, Console.Write()
, , Console.WriteLine()
a corresponding method of operation of these will turn to Console.In
and Console.Out
.