在C#中的FileReader类FileReader

2023-09-04 05:17:21 作者:倾城红颜醉

我要寻找快班与文本文件,舒适的阅读不同的对象(如NextInt32,NextDouble,NextLine方法等)工作。你能指点我什么事?

I am looking for fast class for to work with text files and comfortable reading different object (methods like NextInt32, NextDouble, NextLine, etc). Can you advice me something?

编辑: BinaryReader在差班在我的情况。我的数据格式不是二进制。我有一个文件

BinaryReader is bad class in my case. Format of my data is not binary. I have file like

1 2 3
FirstToken NextToken
1.23 2,34

和我想读取该文件与code这样的:

And I want read this file with code like:

int a = FileReader.NextInt32();
int b = FileReader.NextInt32();
int c = FileReader.NextInt32();
int d = FileReader.NextString();
int e = FileReader.NextString();
int f = FileReader.NextDouble();
int g = FileReader.NextDouble();

EDIT2:我​​要寻找从Java模拟扫描

I am looking for analog Scanner from Java

推荐答案

我要加入这个作为一个单独的答案,因为它是从我已经给出了答案截然不同。以下是你可以开始创建自己的扫描仪类:

I'm going to add this as a separate answer because it's quite distinct from the answer I already gave. Here's how you could start creating your own Scanner class:

class Scanner : System.IO.StringReader
{
  string currentWord;

  public Scanner(string source) : base(source)
  {
     readNextWord();
  }

  private void ReadNextWord()
  {
     System.Text.StringBuilder sb = new StringBuilder();
     char nextChar;
     int next;
     do
     {
        next = this.Read();
        if (next < 0)
           break;
        nextChar = (char)next;
        if (char.IsWhiteSpace(nextChar))
           break;
        sb.Append(nextChar);
     } while (true);
     while((this.Peek() >= 0) && (char.IsWhiteSpace((char)this.Peek())))
        this.Read();
     if (sb.Length > 0)
        currentWord = sb.ToString();
     else
        currentWord = null;
  }

  public bool HasNextInt()
  {
     if (currentWord == null)
        return false;
     int dummy;
     return int.TryParse(currentWord, out dummy);
  }

  public int NextInt()
  {
     try
     {
        return int.Parse(currentWord);
     }
     finally
     {
        readNextWord();
     }
  }

  public bool HasNextDouble()
  {
     if (currentWord == null)
        return false;
     double dummy;
     return double.TryParse(currentWord, out dummy);
  }

  public double NextDouble()
  {
     try
     {
        return double.Parse(currentWord);
     }
     finally
     {
        readNextWord();
     }
  }

  public bool HasNext()
  {
     return currentWord != null;
  }
}
相关推荐
 
精彩推荐
图片推荐