【txtファイルの読み書き】
パソコンや携帯電話には動画ファイル、画像ファイル、テキストファイルなどさまざまなファイルがありますが、その中でもtxtファイルの読み書きが最も簡単で、方法もたくさんあります。
StreamReader と StreamWriter の使用
//读取文件
string path = @"C:\example.txt"; // 文件路径
using (StreamReader reader = new StreamReader(path))//使用using语句来确保资源被正确释放,以避免资源泄漏
{
string line;
while ((line = reader.ReadLine()) != null) // 逐行读取文件内容,每次读取一行,读取到末尾的时候为空
{
Console.WriteLine(line); // 输出每行内容到控制台
}
}
//写入文件
string path = @"C:\example.txt"; // 文件路径
using (StreamWriter writer = new StreamWriter(path))
{
string content = "Hello, World!"; // 要写入文件的内容
writer.WriteLine(content); // 写入一行内容到文件
}
TextReader と TextWriter の使用
//读取文件
string path = @"C:\example.txt"; // 文件路径
using (TextReader reader = new StreamReader(path))
{
string line;
while ((line = reader.ReadLine()) != null) // 逐行读取文件内容
{
Console.WriteLine(line); // 输出每行内容到控制台
}
}
//写入文件
string path = @"C:\example.txt"; // 文件路径
using (TextReader reader = new StreamReader(path))
{
string line;
while ((line = reader.ReadLine()) != null) // 逐行读取文件内容
{
Console.WriteLine(line); // 输出每行内容到控制台
}
}
ファイルストリームを使用する
//读取文件
string path = @"C:\example.txt"; // 文件路径
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
{
using (StreamReader reader = new StreamReader(fs))
{
string line;
while ((line = reader.ReadLine()) != null) // 逐行读取文件内容
{
Console.WriteLine(line); // 输出每行内容到控制台
}
}
}
//写入文件
string path = @"C:\example.txt"; // 文件路径
using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
{
using (StreamWriter writer = new StreamWriter(fs))
{
string content = "Hello, World!"; // 要写入文件的内容
writer.WriteLine(content); // 写入一行内容到文件
}
}
File クラスが提供する静的メソッドを使用する
上記のメソッドはコードが非常に長いため、一般的には使用することはほとんどありませんが、File クラスが提供する静的メソッドを使用する方が便利です。ファイルが非常に大きい場合でも、上記の方法を使用してファイルを読み取る必要があります。そうしないと、一度にすべてを読み取るとメモリが爆発してしまいます。
書き込みを追加したい場合は、上記の方法を使用する必要があります。たとえば、StreamWriter のパラメーターを true に設定するだけです。 StreamWriter sw = new StreamWriter(filePath, true);
//读取文件
string path = @"C:\example.txt"; // 文件路径
string content = File.ReadAllText(path); // 读取整个文件内容
Console.WriteLine(content); // 输出文件内容到控制台
//写入文件
string path = @"C:\example.txt"; // 文件路径
string content = "Hello, World!"; // 要写入文件的内容
File.WriteAllText(path, content); // 将内容写入文件
//上面是一次性读取写入,得到的对象是一个非常大的string,但有时我们需要逐行处理,就要逐行读取写入
string path = @"C:\example.txt"; // 文件路径
string[] lines = File.ReadAllLines(path); // 读取所有行
foreach (string line in lines)
{
Console.WriteLine(line); // 在控制台输出每一行
}
string path = @"C:\example.txt"; // 文件路径
string[] lines = { "第一行内容", "第二行内容", "第三行内容" }; // 字符串数组,每个元素将成为一行
File.WriteAllLines(path, lines); // 将字符串数组中的所有元素写入到文件中
テキストエンコーディング
読み取ったコンテンツが文字化けしている場合は、テキストのエンコーディングを理解し、テキストの読み取りおよび書き込み時にテキスト エンコーディングのパラメーターを渡すことをお勧めします。
【バイナリファイルの読み書き】
BinaryWriter と BinaryReader の使用
ディスクにはバイナリ データのみが保存され、テキスト ファイルは最終的にバイナリ ファイルとして保存されることがわかっています。読み書きするインターフェイスを呼び出すときに文字列を使用しますが、最後に byte[] を指定する必要があります。層。これには、string から byte[] へのエンコードと、byte[] から string へのデコードが含まれますが、テキスト ファイルの場合は、特定のエンコードとデコードの規則があり、それらを気にする必要はありません。
バイナリ ファイルを読み書きするには、エンコード ルールとデコード ルールを自分で設定する必要があります。エンコード、デコードの種類は文字列に限らず、様々な種類が考えられる。
//写入文件
using (BinaryWriter writer = new BinaryWriter(File.Open("file.bytes", FileMode.Create)))
{
bool boolValue = true;
writer.Write(boolValue);
int intValue = 123;
writer.Write(intValue);
float floatValue = 3.14f;
writer.Write(floatValue);
double doubleValue = 3.1415926;
writer.Write(doubleValue);
char charValue = 'A';
writer.Write(charValue);
string content = "永恒之星";
byte[] bytes = Encoding.UTF8.GetBytes(content);
writer.Write(bytes.Length); // 写入字符串长度
writer.Write(bytes); // 写入字符串字节数组
}
ファイルを読み取るときは、書き込まれた順序で 1 つずつ読み取ってください。
//读取文件
using (BinaryReader reader = new BinaryReader(File.Open("file.bytes", FileMode.Open)))
{
bool boolValue = reader.ReadBoolean();
Debug.Log(boolValue);
int intValue = reader.ReadInt32();
Debug.Log(intValue);
float floatValue = reader.ReadSingle();
Debug.Log(floatValue);
double doubleValue = reader.ReadDouble();
Debug.Log(doubleValue);
char charValue = reader.ReadChar();
Debug.Log(charValue);
int length = reader.ReadInt32();
byte[] bytes = reader.ReadBytes(length);
string content = Encoding.UTF8.GetString(bytes);
Debug.Log(content);
}
メモリーストリームを使用する
上記の問題は、一度に 1 つずつ読み書きされ、複数の IO オーバーヘッドが発生することですが、MemoryStream を使用すると、ファイルの内容を一度にメモリに読み書きし、その後ディスクに読み書きすることができます。
また、データを一行一行読み書きするのですが、データが1万件あれば、当然1万行のコードを書くことは不可能なので、同じ種類のデータに対して、データ数を調整し、for ループを使用してコード量を削減します。
//写入文件
using (MemoryStream ms = new MemoryStream())
{
using (BinaryWriter writer = new BinaryWriter(ms))
{
bool boolValue = true;
writer.Write(boolValue);
int count = 5;
writer.Write(count);
for (int i = 0; i < count; i++)
{
int intValue = 123;
writer.Write(intValue);
}
float floatValue = 3.14f;
writer.Write(floatValue);
double doubleValue = 3.1415926;
writer.Write(doubleValue);
char charValue = 'A';
writer.Write(charValue);
string content = "永恒之星";
byte[] bytes = Encoding.UTF8.GetBytes(content);
writer.Write(bytes.Length); // 写入字符串长度
writer.Write(bytes); // 写入字符串字节数组
}
File.WriteAllBytes("file.bytes", ms.ToArray());//一次性写入磁盘
}
//读取文件
using (MemoryStream ms = new MemoryStream(File.ReadAllBytes("file.bytes")))//一次性从磁盘读取数据
{
using (BinaryReader reader = new BinaryReader(ms))
{
bool boolValue = reader.ReadBoolean();
Debug.Log(boolValue);
int count = reader.ReadInt32();
for (int i = 0; i < count; i++)
{
int intValue = reader.ReadInt32();
Debug.Log(intValue);
}
float floatValue = reader.ReadSingle();
Debug.Log(floatValue);
double doubleValue = reader.ReadDouble();
Debug.Log(doubleValue);
char charValue = reader.ReadChar();
Debug.Log(charValue);
int length = reader.ReadInt32();
byte[] bytes = reader.ReadBytes(length);
string content = Encoding.UTF8.GetString(bytes);
Debug.Log(content);
}
}
拡大する
さまざまな種類のデータを異なるバイナリ ファイルに書き込む必要があり、後でデータ構造を変更する可能性がある場合、毎回自分で読み書きするのは非常に面倒で、メンテナンス コストも高くなります。読み取りと書き込みを支援するシリアル化ツールを使用する必要がありますが、必要なのはデータ構造を定義してデータを入力することだけです。これらのツールには、BinaryFomatter、ProtoBuf、FlatBuffer などがありますが、適切なツールを選択することがより重要です。