C# study notes text input/output

Text I/O using Reader and Writer

TextWriterCategory and TextReaderclass is an abstract class-based text, an important subclass thereof comprising: StreamWriter, , StreamReaderstream processing operation; StringWriter, StringReaderprocessing operation of the string. Note: For C programmers, it is StreamWritersimilar to printf()or fprintf(), and StringWritersimilar sprintf().

1.TextWriter

TextWriterIs an abstract base class, it contains the following subclasses:

  • ① Used to write HTML for the browser clientHtmlTextWriter
  • ② Used to write text to the HTTP response object in the ASP.NET web pageHttpWriter
  • ③ Use the indentation control to write textIndentedTextWriter
  • ④ Write characters to the streamStringWriter
  • ⑤ Write characters to the stringStringWriter

TextWriterThere are 3 attributes:, Encodingused 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 resources
  • Dispose, Release resources related to TextWriter
  • Flush, To write the unregistered data kept in the TextWriter buffer
  • Synchronized, A thread-safe package for creating TextWriter objects
  • Write, Write data to the stream
  • WriteLine, 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: Streamthe Write()method of writing is bytes, BinaryWriterthe Writer()method is to write the basic data types in a primitive way.
Write()The method can objectwrite 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 TextWriterthe method. In fact, the method calls the same method.
The static Synchronized()method can TextWritercreate a thread-safe wrapper to ensure its safety, so that TextWritertwo 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-8that 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.Textthe ASCII and UTF-7 encoding provided by the namespace, or System.Text.Encodingcreate 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 FileStreamit.
StreamWriterThere is a AutoFlushproperty, 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 StreamWriteras effective as allowing its output content to be buffered. BaseStreamProperties provide access to the basic Stream object.
Apart from the TextWriteraddition to the methods inherited, the StreamWriterclass does not add any new method, but a heavy load, and for writing character string to the flow Write()method.

3.StringWriter method

StringWriterUsed 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 Stringit 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

TextReaderThe class is used to read strings. TextReaderThe class has two subclasses StreamReaderand StringReader. This class contains TextWriterfewer methods than the class, but the processing method is the same:

  • Close, Close TextReader and release all related resources
  • Peek, Browse the next character, but don’t remove it from the input stream
  • Read, Read the characters into the character array
  • ReadBlock, Continue to read characters into a character array or block until enough characters are read or the end of the file is reached
  • ReadLine, Read in a line of characters and return it as a string
  • ReadToEnd, Has been read to the end of the stream, and all characters are returned as a string
  • Synchronized, Create a thread-safe package of TextReader

5.StreamReader

StreamReaderThe class supports character-oriented input in streams, so this class can be used to read text line by line from a file. StreamReaderAny 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 Streamreference, it is also possible not to specify the encoding method

The StreamReader class has two attributes:, BaseStreamused to return a reference to the Stream contained in the class CurrentEncoding;, used to return the character encoding used by the current reader object.
StreamReaderThere 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:
Insert picture description here

Use File's text file function

The processing of text files is more commonly used, so .NET Frameworka 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 file
  • File.ReadAllLines(path, encoding)Read an array of all lines of a file
  • File.WriteAllText(path, text, encoding)Write text to a file
  • File.WriteAllLines(path, lines, encoding)Write the text array to a file
  • File.AppendAllText(path, text, encoding)Append text to a file
  • FIle.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 Consoleto handle the Operations Console. Console has three staticattributes: Console.In, , Console.Out, Console.Errorrespectively, in the system standard input, standard output and standard error associated.
Console.InIs TextReaderthe object of the class, Console.Outand Console.Erroris TextWriterthe 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.Inand Console.Out.

Guess you like

Origin blog.csdn.net/qq_45349225/article/details/114419443