개발 관련/SW, App 관련

StreamWrite를 이용한 txt 파일 쓰기

by 소서리스25 2023. 4. 15.
반응형

 

StreamWrite를 이용한 txt 파일 쓰기

 

 

지난번에 StreamReader에 이어 이번에는 StreamWrite를 이용한 text에 파일을 쓰는 방법이다.

대부분 동일한 방식으로 진행된다.

 

해당 내용도 동일하게 마이크로소프트 사이트에 가면 StreamWrite 클래스가 있다.

 

우선 text 파일에 다음과 같은 text를 쓰게 한 뒤 제대로 읽었는지는 지난번에 

알아본 StreamReader를 이용해서 확인해 보도록 한다.

그럼 이를 토대로 필요한 사항을 정리한 코드를 다음과 같이 살펴 보자.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
using System.IO;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class TestStream : MonoBehaviour
{
    string _filePath = "./setup.txt";
 
    void Start()
    {
        WriteTextFile(_filePath);
    }
 
    void WriteTextFile(string filePath)
    {
        StreamWriter wd = new StreamWriter(filePath);
 
        wd.WriteLine("setup data");
        wd.WriteLine("9600 baudrate");
        wd.WriteLine("com3 serial");
        wd.WriteLine("8 bit");
 
        wd.Close();
 
        ReadTextFile(_filePath);
    }
 
    void ReadTextFile(string filePath)
    {
        StreamReader rd = new StreamReader(filePath);
        string _line = "";
 
        while ((_line = rd.ReadLine()) != null)
        {
            print(_line);
        }
 
        rd.Close();
    }
}
cs

 

그리고 결과를 콘솔에서 확인해 보면 다음과 같이 정상적으로 저장하고 다시 읽은 것을 

확인 할 수 있다.

 

 

반응형

댓글