C#의 TextReader

WBOY
풀어 주다: 2024-09-03 15:22:54
원래의
1001명이 탐색했습니다.

C#의 TextReader는 텍스트 파일에서 텍스트나 일련의 문자를 읽는 데 사용됩니다. TextReader 클래스는 System.IO 네임스페이스 아래에 있습니다. 스트림과 문자열에서 각각 문자를 읽는 데 사용되는 StreamReader 및 StringReader의 추상 기본 클래스입니다. TextReader는 추상 클래스이기 때문에 객체를 생성할 수 없습니다. TextReader는 기본적으로 스레드로부터 안전하지 않습니다. TextReader 클래스를 파생하는 클래스는 유용한 TextReader 인스턴스를 만들기 위해 Peek() 및 Read() 메서드를 최소한으로 구현해야 합니다.

구문:

TextReader 생성 구문은 다음과 같습니다.

TextReader text_reader = File.OpenText(file_path);
로그인 후 복사
로그인 후 복사

위 명령문은 'file_path'에 지정된 위치에 있는 파일을 엽니다. 그런 다음 text_reader의 도움으로 TextReader 클래스의 메서드를 사용하여 파일의 내용을 읽을 수 있습니다.

아래와 같이 'using' 블록을 사용하여 TextReader를 만들 수도 있습니다.

using(TextReader text_reader = File.OpenText(file_path))
{
//user code
}
로그인 후 복사

'using' 블록 작업의 장점은 객체 작업이 완료되고 객체가 더 이상 필요하지 않은 후 내부에 지정된 객체가 획득한 메모리를 해제한다는 것입니다.

C#에서 TextReader는 어떻게 작동하나요?

TextReader를 사용하려면 코드에 System.IO 네임스페이스를 가져와야 합니다. TextReader는 추상 클래스이므로 'new' 키워드를 사용하여 인스턴스를 직접 생성할 수는 없지만 아래와 같이 File 클래스의 OpenText() 메서드를 사용하여 동일한 결과를 얻을 수 있습니다.

TextReader text_reader = File.OpenText(file_path);
로그인 후 복사
로그인 후 복사

OpenText() 메서드는 파일 위치를 입력으로 가져온 다음 읽기 위해 동일한 위치에 있는 기존 UTF-8 인코딩 텍스트 파일을 엽니다.

File.OpenText() 메서드는 TextReader의 파생 클래스인 StreamReader 클래스의 개체를 반환하므로 코드에서 TextReader 클래스의 유용한 인스턴스를 만드는 데 도움이 됩니다. 이 인스턴스는 TextReader 클래스의 메서드를 호출하여 파일의 내용을 읽는 데 사용할 수 있습니다. TextReader 클래스는 추상 클래스 MarshalByRefObject에서 파생됩니다. 상속 계층 구조는 다음과 같습니다.

객체 → MarshalByRefObject → TextReader

StreamReader와 StringReader라는 두 가지 파생 클래스를 사용하여 TextReader로 작업할 수 있습니다.

  • StreamReader: 특정 인코딩의 바이트 스트림에서 문자를 읽는 데 사용됩니다.
  • StringReader: 문자열에서 텍스트를 읽는 데 사용됩니다.

다음 표에서 TextReader의 몇 가지 중요한 메소드를 찾아보세요.

Method Description
Close() It is used to close the TextReader and to release any system resources associated with it.
Dispose() It is used to release all the resources used by an object of TextReader.
Peek() It is used to read the next character without changing the state of the reader and it returns the next available character without actually reading it from the reader.
Read() It is used to read the next character from the text reader and it also advances the character position by one character.
ReadLine() It is used to read a line of characters from the text reader and it also returns the data as a string.
ReadToEnd() It is used to read all characters from the current position to the end of the text reader and it returns them as one string.
방법 설명 닫기() TextReader를 닫고 이와 관련된 시스템 리소스를 해제하는 데 사용됩니다. Dispose() TextReader 개체에서 사용하는 모든 리소스를 해제하는 데 사용됩니다. Peek() 리더의 상태를 변경하지 않고 다음 문자를 읽는 데 사용되며 리더에서 실제로 읽지 않고 사용 가능한 다음 문자를 반환합니다. 읽기() 텍스트 리더에서 다음 문자를 읽는 데 사용되며 문자 위치를 한 문자씩 앞으로 이동하기도 합니다. ReadLine() 텍스트 리더에서 한 줄의 문자를 읽는 데 사용되며 데이터를 문자열로 반환하기도 합니다. ReadToEnd() 현재 위치부터 텍스트 리더 끝까지의 모든 문자를 읽어서 하나의 문자열로 반환하는데 사용됩니다.

Examples of TextReader in C#

We can pass a text file name in a TextReader constructor to create an object. Following are the different examples of TextReader in C#.

Example #1

Reading a line of a file using the ReadLine() method of TextReader.

Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApp3
{
public class Program
{
public static void Main()
{
string file = @"E:\Content\TextReader.txt";
try
{
if (File.Exists(file))
{
// opening the text file and reading a line
using (TextReader textReader = File.OpenText(file))
{
Console.WriteLine(textReader.ReadLine());
}
}
else
{
Console.WriteLine("File does not exist!");
}
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
로그인 후 복사

Output:

C#의 TextReader

Example #2

Reading five characters from a file using the ReadBlock() method of TextReader.

Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApp3
{
public class Program
{
public static void Main()
{
string file = @"E:\Content\TextReader.txt";
try
{
if (File.Exists(file))
{
//Opening the text file and reading 5 characters
using (TextReader textReader = File.OpenText(file))
{
char[] ch = new char[5];
textReader.ReadBlock(ch, 0, 5);
Console.WriteLine(ch);
}
}
else
{
Console.WriteLine("File does not exist!");
}
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
로그인 후 복사

Output:

C#의 TextReader

Example #3

Reading the whole content of a text file using the ReadToEnd() method of TextReader.

Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApp3
{
public class Program
{
public static void Main()
{
string file = @"E:\Content\TextReader.txt";
string content = String.Empty;
try
{
if (File.Exists(file))
{
//Opening a text file and reading the whole content
using (TextReader tr = File.OpenText(file))
{
content = tr.ReadToEnd();
Console.WriteLine(content);
}
}
else
{
Console.WriteLine("File does not exist!");
}
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
로그인 후 복사

Output:

C#의 TextReader

Example #4

Reading the content of a text file using TextReader and writing it to another file.

Code:

using System;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApp3
{
public class Program
{
public static void Main()
{
string fileToRead = @"E:\Content\TextReader.txt";
string fileToWrite = @"E:\Content\TextReaderAndWriter.txt";
StringBuilder content = new StringBuilder();
string str = String.Empty;
try
{
//checking if the file exists to read
if (File.Exists(fileToRead))
{
//Opening a text file and reading the whole content
using (TextReader textReader = File.OpenText(fileToRead))
{
while ((str = textReader.ReadLine()) != null)
{
content.Append("\n" + str);
}
}
}
else
{
Console.WriteLine("File does not exist!");
}
//checking if the file to write content already exists
if (File.Exists(fileToWrite))
{
File.Delete(fileToWrite);
}
//creating file if it does not exist
using (TextWriter textWriter = File.CreateText(fileToWrite))
{
textWriter.WriteLine(content);
}
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
로그인 후 복사

Output:

C#의 TextReader

Conclusion

  • TextReader is an abstract class that is used to read text or sequential series of characters from a text file.
  • StreamReader and StringReader are two derived classes of TextReader with the help of which we can implement the methods of TextReader to read content from the text files.

위 내용은 C#의 TextReader의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!