C#의 TextWriter

PHPz
풀어 주다: 2024-09-03 15:22:45
원래의
186명이 탐색했습니다.

TextWriter는 파일에 텍스트를 쓰는 데 사용됩니다. 다음은 C#의 TextWriter와 관련된 몇 가지 중요한 사항입니다. TextWriter는 IO 네임스페이스 아래에 있는 추상 클래스입니다. 일련의 문자를 순차적으로 파일에 쓰는 데 사용됩니다. 스트림과 문자열에 각각 문자를 쓰는 데 사용되는 StreamWriter 및 StringWriter의 기본 클래스입니다.

기본적으로 스레드로부터 안전하지 않습니다. 추상클래스이므로 객체를 생성할 수 없습니다. TextWriter를 구현하는 모든 클래스는 유용한 인스턴스를 생성하기 위해 Write(Char) 메서드를 최소한으로 구현해야 합니다.

설명이 포함된 구문

TextWriter text_writer = File.CreateText(file_path);
로그인 후 복사
로그인 후 복사

위 명령문은 지정된 위치(file_path)에 파일이 없으면 새 파일을 생성합니다. 그런 다음 text_writer를 사용하여 TextWriter 클래스의 메서드를 호출하고 C#에서 파일 작업을 쉽게 수행할 수 있습니다.

다음과 같은 using 문을 사용하여 TextWriter를 만들 수 있습니다.

using(TextWriter text_writer = File.CreateText(file_path))
{
//user code
}
로그인 후 복사

작업이 완료되고 더 이상 필요하지 않으면 using 블록에 지정된 개체를 해제하도록 .NET에 지시하므로 using 문과 함께 TextWriter를 사용하는 것이 좋습니다.

C#에서 TextWriter가 어떻게 작동하나요?

TextWriter를 사용하려면 먼저 System.IO 네임스페이스를 가져와야 합니다. 이제 'new' 키워드를 사용하여 TextWriter 인스턴스를 직접 생성할 수 없습니다. 이는 추상 클래스이기 때문입니다. 따라서 인스턴스를 생성하려면 다음과 같이 File 클래스의 CreateText() 메서드를 사용합니다.

TextWriter text_writer = File.CreateText(file_path);
로그인 후 복사
로그인 후 복사

이 방법은 쓰기 위해 열 파일의 경로를 사용합니다. UTF-8로 인코딩된 텍스트를 쓰기 위한 파일을 생성하거나 엽니다. 파일이 이미 존재하는 경우 해당 내용을 덮어씁니다.

TextWriter의 파생 클래스인 StreamWriter의 개체를 반환하므로 TextWriter 클래스의 인스턴스를 생성하는 데 도움이 됩니다. 이제 이 인스턴스의 도움으로 TextWriter의 메서드를 호출하여 파일에 텍스트를 쓸 수 있습니다.

TextWriter는 추상 클래스 MarshalByRefObject의 파생 클래스입니다. 상속 계층 구조는 다음과 같습니다.

객체 ——–> MarshalByRefObject ——–> 텍스트라이터

StreamWriter와 마찬가지로 TextWriter 클래스에서 파생되고 TextWriter 멤버에 대한 구현을 제공하는 다른 클래스도 있습니다. TextWriter로 작업할 수 있는 파생 클래스 목록을 아래에서 찾아보세요.

  • IndentedTextWriter: 탭 문자열을 삽입하고 현재 들여쓰기 수준을 추적하는 데 사용됩니다.
  • StreamWriter: 특정 인코딩으로 스트림에 문자를 쓰는 데 사용됩니다.
  • StringWriter: 문자열에 정보를 쓰는 데 사용됩니다. 정보는 기본 StringBuilder에 저장됩니다.
  • HttpWriter: 내장된 HttpResponse 개체를 통해 액세스할 수 있는 TextWriter 클래스의 개체를 제공합니다.
  • HtmlTextWriter: ASP.NET 서버 제어 출력 스트림에 마크업 문자와 텍스트를 쓰는 데 사용됩니다.

이제 다음과 같은 TextWriter의 몇 가지 중요한 방법에 대해 논의하겠습니다.

Method Description
Close() It is used to close the current writer and it releases any system resources associated with that writer.
Dispose() It is used to release all the resources used by the TextWriter object.
Flush() It is used to clear all buffers for the current writer and causes any buffered data to be written to the underlying device.
Synchronized(TextWriter) It is used to create a thread-safe wrapper around the specified TextWriter.
Write(Char) It is used to write a character to the text stream.
Write(String) It is used to write the string to the text stream.
WriteAsync(Char) It is used to write the character to the text stream asynchronously.
WriteLine() It is used to write line terminator to the text stream.
WriteLineAsync(String) It is used to write the string to the text stream asynchronously followed by a line terminator.
방법 설명 닫기() 현재 작성기를 닫고 해당 작성기와 관련된 모든 시스템 리소스를 해제하는 데 사용됩니다. 처리() TextWriter 개체에서 사용하는 모든 리소스를 해제하는 데 사용됩니다. 플러시() 현재 기록기에 대한 모든 버퍼를 지우는 데 사용되며 버퍼링된 모든 데이터가 기본 장치에 기록되도록 합니다. 동기화됨(TextWriter) 지정된 TextWriter 주위에 스레드로부터 안전한 래퍼를 만드는 데 사용됩니다. 쓰기(문자) 텍스트 스트림에 문자를 쓰는 데 사용됩니다. 쓰기(문자열) 텍스트 스트림에 문자열을 쓰는 데 사용됩니다. WriteAsync(Char) 문자를 텍스트 스트림에 비동기적으로 쓰는 데 사용됩니다. WriteLine() 텍스트 스트림에 줄 종결자를 쓰는 데 사용됩니다. WriteLineAsync(문자열) 문자열을 텍스트 스트림에 비동기적으로 쓰고 그 뒤에 줄 종결자가 오는 데 사용됩니다.

Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApp2
{
class Program
{
public static void Main()
{
string file = @"E:\Content\textWriter.txt";
// check if the file exists
try
{
if (File.Exists(file))
{
File.Delete(file);
}
// create the file
using (TextWriter writer = File.CreateText(file))
{
writer.WriteLine("TextWriter is an abstract class under " +
"System.IO namespace. It is used to write sequential " +
"series of characters into a file. It is the base class " +
"of StreamWriter and StringWriter which is used to " +
"write characters to streams and strings respectively. " +
"By default, it is not thread safe. " +
"As it is an abstract class, its object cannot be created. " +
"Any class implementing TextWriter must minimally implement " +
"its Write(Char) method to create its useful instance. ");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
로그인 후 복사

Output:

C#의 TextWriter

We can asynchronously write characters to stream by using WriteAsync(Char) method such as:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApp2
{
public class Program
{
public static void Main(string[] args)
{
WriteCharAsync();
}
public static async void WriteCharAsync()
{
string file = @"E:\Content\textWriterAsync.txt";
try
{
//check if file already exists
if (File.Exists(file))
{
File.Delete(file);
}
using (StreamWriter writer = File.CreateText(file))
{
await writer.WriteLineAsync("TextWriter is an abstract class under "+
"System.IO namespace. It is used to write sequential " +
"series of characters into a file. It is the base class " +
"of StreamWriter and StringWriter which is used to " +
"write characters to streams and strings respectively. " +
"By default, it is not thread safe. " +
"As it is an abstract class, its object cannot be created. " +
"Any class implementing TextWriter must minimally implement " +
"its Write(Char) method to create its useful instance. ");
await writer.WriteLineAsync("We are writing characters " +
"asynchronously.");
}
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
로그인 후 복사

Output:

C#의 TextWriter

Conclusion

TextWriter is used to write text or sequential series of characters to a file. A class derived from the TextWriter class needs to provide implementation to any of the members of the TextWriter. Write() methods of TextWriter with primitive data types as parameters write out values as strings.

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

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