c# – 读取和写入文本文件时出现意外输出
发布时间:2020-12-15 17:26:02 所属栏目:百科 来源:网络整理
导读:我对C#中的文件有点新,我遇到了问题.从文件读取并复制到另一个文件时,最后一块文本没有被写入.以下是我的代码: StringBuilder sb = new StringBuilder(8192);string fileName = "C:...rest of path...inputFile.txt";string outputFile = "C:...rest of pat
我对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,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,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,我将非常感谢您的建议. 解决方法
有几个“陷阱”:
> c无法更改(它是foreach迭代变量),您需要复制它才能在写入之前进行处理 像这样更改代码看起来像是有效的: //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); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |