我对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 }
你能帮我找出问题的根源吗?
解决方法
有几个“陷阱”:
> c无法更改(它是foreach迭代变量),您需要复制它才能在写入之前进行处理
>你必须跟踪缓冲区的大小,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); }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。