replacing \n with \r\n in a large text file
I have a large text file with a lot of \n that I need to replace with开发者_如何学JAVA \r\n. With small text files, I was using the ReadToEnd method to get the file as a string and then use the Replace method and then write the string to a file. With a big file, however, I get an OutOfMemory exception because the string is too big. Any help would be greatly appreciated. Thanks.
private void foo() {
StreamReader reader = new StreamReader(@"D:\InputFile.txt");
StreamWriter writer = new StreamWriter(@"D:\OutputFile.txt");
string currentLine;
while (!reader.EndOfStream) {
currentLine = reader.ReadLine();
writer.Write(currentLine + "\r\n");
}
reader.Close();
writer.Close();
}
This should resolve your problem. Please note, that reader.ReadLine() cuts of the trailing "\n".
DiableNoir's solution is the right idea, but the implementation is buggy and it needs some explanation. Here's an improved one:
using (var reader = new StreamReader(@"D:\InputFile.txt"))
using (var writer = new StreamWriter(@"D:\OutputFile.txt")) // or any other TextWriter
{
while (!reader.EndOfStream) {
var currentLine = reader.ReadLine();
writer.Write(currentLine + "\r\n");
}
}
You use a TextReader
for input and a TextWriter
for output (this one might direct to a file or to an in-memory string). reader.ReadLine
will not return the line ending as part of the line, so you need to write it explicitly (instead of using string.Replace
, which will not accomplish anything at all).
Also, exactly because you will never see \n
or \r
as part of currentLine
, this program is safe to run again on the output it has produced (in this case its output will be exactly identical to its input). This would not be the case if currentLine
included the line ending, because it would change \n
to \r\n
the first time, and then make it \r\r\n
the second time, etc.
You could use Read and specify how many bytes to read each time. Such as read the file in 10 MB chunks.
Or if you need like a larger buffer you can use StreamReader.ReadBlock();
精彩评论