gpt4 book ai didi

c# - 读取和写入文本文件时出现意外输出

转载 作者:行者123 更新时间:2023-11-30 12:32:53 26 4
gpt4 key购买 nike

我对 C# 中的文件有点陌生,遇到了问题。从一个文件读取并复制到另一个文件时,最后一段文本没有被写入。下面是我的代码:

StringBuilder sb = new StringBuilder(8192);
string fileName = "C:...rest of path...inputFile.txt";
string outputFile = "C:...rest of path...outputFile.txt";

using (StreamReader reader = File.OpenText(fileName))
{
char[] buffer = new char[8192];
while ((reader.ReadBlock(buffer, 0, buffer.Length)) != 0)
{
foreach (char c in buffer)
{
//do some function on char c...
sb.Append(c);
}

using (StreamWriter writer = File.CreateText(outputFile))
{
writer.Write(sb.ToString());
}
}
}

我的目标是以缓冲方式读取和写入文本文件。在 Java 中,我将通过以下方式实现:

public void encrypt(File inputFile, File outputFile) throws IOException
{
BufferedReader infromfile = null;
BufferedWriter outtofile = null;

try
{
String key = getKeyfromFile(keyFile);
if (key != null)
{
infromfile = new BufferedReader(new FileReader(inputFile));
outtofile = new BufferedWriter(new FileWriter(outputFile));
char[] buffer = new char[8192];
while ((infromfile.read(buffer, 0, buffer.length)) != -1)
{
String temptext = String.valueOf(buffer);
//some changes to temptext are done
outtofile.write(temptext);
}
}
}
catch (FileNotFoundException exc)
{
} // and all other possible exceptions
}

您能帮我找出问题的根源吗?

如果您认为可能有更好的方法来实现文本文件的缓冲 i/o,我将非常感谢您的建议。

最佳答案

有几个“陷阱”:

  1. c 不能改(是foreach迭代变量),写之前需要copy它以便处理
  2. 您必须跟踪缓冲区的大小,ReadBlock 会用会使您的输出变脏的字符填充它

像这样更改您的代码看起来可行:

//extracted from your code
foreach (char c in buffer)
{
if (c == (char)0) break; //GOTCHA #2: maybe you don't want NULL (ascii 0) characters in your output

char d = c; //GOTCHA #1: you can't change 'c'

// d = SomeProcessingHere();

sb.Append(d);
}

关于c# - 读取和写入文本文件时出现意外输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10637267/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com