开发者

Insert data into text file

I want to insert the data at some positions in the text file without actually overwriting on the existing data. I have two text file. "one.txt" file have 1000 lines, "two.txt" file have 10000 lines. I want to read "one.tx开发者_如何学Got" file content and insert into first 1000 lines of "two.txt" file content(Append the content of "one.txt" to the beginning of "two.txt").

Criteria:

  • Minimum code .
  • Less Memory consumption(irrespective of programming language )
  • Performance (will be considered based on size of the file).


just open up a streamreader for the first file, and a stream writer (in append mode) for the second file. As your reading the first 1000 lines from the first file, insert them into the second.

Something like this:

StreamReader sr = new StreamReader("one.txt");
StreamWriter sw = new StreamWriter("two.txt", true);  //true for append
index i = 0;
while (i < 1000) {
     sw.WriteLine(sr.ReadLine());
     i++;
}

You may want to check for end of file on the StreamReader, but this will give you the general idea....

Based on the new information in OP:

You can use this same type of method, but just create a brand new file, reading the data from the first file, followed by the data from the second file. Once it's inside the new file, replace the original "two.txt".


If you're not limited to c# you can just do the following from a windows command line:

copy one.txt + two.txt three.txt

This would create the file you want, but it would be called three.txt. If you must have it in two.txt, you could simply rename two.txt to something else first and then do the copy append with two.txt as the third parm.


If you only have to do this once, here is some code that will do what you want. I did not compile this, but I believe there are no issues.

string[] linesOne = File.ReadAllLines(pathToFile1);
string[] linesTwo = File.ReadAllLines(pathToFile2);

List<string> result = new List<string>();
for(int i=0;i<1000;i++)
{
   result.Add(linesOne[i]);
}
result.AddRange(linesTwo);

File.WriteAllLines(pathToFile2, result);

Hope this gets you started.

Bob

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜