我有一个名为的文本文件C:/test.txt
:
1 2 3 4 5 6
我想使用读取这个文件中的每个数字StreamReader
。
我怎样才能做到这一点?
我有一个名为的文本文件C:/test.txt
:
1 2 3 4 5 6
我想使用读取这个文件中的每个数字StreamReader
。
我怎样才能做到这一点?
您真的需要使用 aStreamReader
来执行此操作吗?
IEnumerable<int> numbers =
Regex.Split(File.ReadAllText(@"c:\test.txt"), @"\D+").Select(int.Parse);
(显然,如果一次读取整个文件不切实际,那么您需要流式传输它,但如果您能够使用File.ReadAllText
,那么这就是我认为的方法。)
为了完整起见,这是一个流媒体版本:
public IEnumerable<int> GetNumbers(string fileName)
{
using (StreamReader sr = File.OpenText(fileName))
{
string line;
while ((line = sr.ReadLine()) != null)
{
foreach (string item in Regex.Split(line, @"\D+"))
{
yield return int.Parse(item);
}
}
}
}
using (StreamReader reader = new StreamReader(stream))
{
string contents = reader.ReadToEnd();
Regex r = new Regex("[0-9]");
Match m = r.Match(contents );
while (m.Success)
{
int number = Convert.ToInt32(match.Value);
// do something with the number
m = m.NextMatch();
}
}
如果您想要从文件中读取整数并将它们存储在列表中,那么类似的方法可能会奏效。
try
{
StreamReader sr = new StreamReader("C:/test.txt"))
List<int> theIntegers = new List<int>();
while (sr.Peek() >= 0)
theIntegers.Add(sr.Read());
sr.Close();
}
catch (Exception e)
{
//Do something clever to deal with the exception here
}
大文件的解决方案:
class Program
{
const int ReadBufferSize = 4096;
static void Main(string[] args)
{
var result = new List<int>();
using (var reader = new StreamReader(@"c:\test.txt"))
{
var readBuffer = new char[ReadBufferSize];
var buffer = new StringBuilder();
while ((reader.Read(readBuffer, 0, readBuffer.Length)) > 0)
{
foreach (char c in readBuffer)
{
if (!char.IsDigit(c))
{
// we found non digit character
int newInt;
if (int.TryParse(buffer.ToString(), out newInt))
{
result.Add(newInt);
}
buffer.Remove(0, buffer.Length);
}
else
{
buffer.Append(c);
}
}
}
// check buffer
if (buffer.Length > 0)
{
int newInt;
if (int.TryParse(buffer.ToString(), out newInt))
{
result.Add(newInt);
}
}
}
result.ForEach(Console.WriteLine);
Console.ReadKey();
}
}
我可能错了,但使用 StreamReader 你不能设置分隔符。但是您可以使用 String.Split() 设置分隔符(在您的情况下是空格?)并将所有数字提取到单独的数组中。
像这样的东西:
using System;
using System.IO;
class Test
{
public static void Main()
{
string path = @"C:\Test.txt";
try
{
if( File.Exists( path ) )
{
using( StreamReader sr = new StreamReader( path ) )
{
while( sr.Peek() >= 0 )
{
char c = ( char )sr.Read();
if( Char.IsNumber( c ) )
Console.Write( c );
}
}
}
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
}
}
像这样的东西应该可以工作:
using (var sr = new StreamReader("C:/test.txt"))
{
var s = sr.ReadToEnd();
var numbers = (from x in s.Split('\n')
from y in x.Split(' ')
select int.Parse(y));
}