我有一个程序来读取百万行文件。每行有一个浮点值。该值将被读入并放入数组中的一个元素中。StreamReader不会停止读取文本文件
using System;
using System.Diagnostics;
using System.IO;
namespace sort1mRandFloat
{
public class Program
{
static void Main()
{
Console.WriteLine("Creating Single array...");
Single[] fltArray = new Single[1000000];
Console.WriteLine("Array created, making string...");
String line;
Console.WriteLine("String created, opening file...");
StreamReader file = new StreamReader(@"C:\\Users\\Aaron\\Desktop\\rand1mFloats.txt");
Console.WriteLine("File opened, creating stopwatch and starting main execution event. See you on the other side.");
int i;
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
while((line = file.ReadLine()) != null)
{
for(i=0; i < 1000000; i++)
{
fltArray[i] = Convert.ToSingle(line);
if (i == 999999)
Console.WriteLine("At 999999");
}
}
file.Close();
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
String elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds/10);
Console.WriteLine("It took " + elapsedTime + " to read a thousand lines into the array.\n");
Console.WriteLine("Element 0 is: " + fltArray[0]);
Console.WriteLine("Element 999999 is: " + fltArray[999999]);
Console.ReadLine();
}
}
}
当此代码在文件上运行时,它不会停止。它正在寻找某种东西来告诉它它已经在瓦片的末尾或者什么东西上,而且它没有找到它。填充999,999个元素后,它将循环回0并重新开始。
此代码或多或少基于微软在其网站上推荐的内容......关于我在做什么错误的任何想法?
该文件可以在下面找到。由于我还没有能够将文件存储在数组中,我不能说它需要多长时间才能工作。文件中有相当多的值。计量连接警告:18 MB文件。
这两个代码块实际上做了稍微不同的事情。第一个不会停留在第1000000条,但第二个是。 – Dirk
@Dirk我假定文件正好有1000000个条目,所以在1000000th之后'ReadLine'将返回'null'。但是,他们有些不同。 – MarcinJuraszek
* Ed McMahon声音* 您是正确的先生! 这是漫长的一天。我一直试图在语言之间转换相同的算法。我想那是从我身边飞过来的。谢谢。 – nerdenator