Чтение в файлах, содержащих определенные символы на C#
-
20-09-2019 - |
Вопрос
У меня есть текстовый файл с именем C:/test.txt
:
1 2 3 4 5 6
Я хочу прочитать каждое число в этом файле, используя StreamReader
.
Как я могу это сделать?
Решение
Вам действительно нужно использовать StreamReader
чтобы сделать это?
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();
}
}
Что-то вроде so может сработать, если вы хотите прочитать целые числа из файла и сохранить их в списке.
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 вы не можете установить delimeter .Но вы можете использовать String.Split() для установки delimeter (в вашем случае это пробел?) и извлечения всех чисел в отдельный массив.
Что-то вроде этого должно сработать:
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));
}
Что- то вроде этого:
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());
}
}
}