读从一个StreamReader线不会消耗? [英] Reading a line from a streamreader without consuming?

查看:134
本文介绍了读从一个StreamReader线不会消耗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法提前读取一行来测试下一行包含特定标记的数据?

Is there a way to read ahead one line to test if the next line contains specific tag data?

我处理,有一个开始标签的格式但没有结束标记。

I'm dealing with a format that has a start tag but no end tag.

我想读一行将其添加到结构,然后测试下面的线,以确保它不是一个新的节点,如果它不继续增加,如果它是接近关闭的结构,使一个新的

I would like to read a line add it to a structure then test the line below to make sure it not a new "node" and if it isn't keep adding if it is close off that struct and make a new one

我能想到的是唯一的解决办法有两个流的读者在同一时间去还挺suffling有办法一起锁步,但似乎wastefull(如果它甚至将工作)

the only solution i can think of is to have two stream readers going at the same time kinda suffling there way along lock step but that seems wastefull (if it will even work)

我需要像偷看但peekline

i need something like peek but peekline

推荐答案

问题是底层的流甚至可能不是可查找。如果你看一看流读取器实现它使用了一个缓冲区,以便其可以实现TextReader.Peek(),即使流处于不可搜索。

The problem is the underlying stream may not even be seekable. If you take a look at the stream reader implementation it uses a buffer so it can implement TextReader.Peek() even if the stream is not seekable.

您可以编写一个简单的适配器读取下一行并在内部进行缓冲,这样的事情:

You could write a simple adapter that reads the next line and buffers it internally, something like this:

 public class PeekableStreamReaderAdapter
    {
        private StreamReader Underlying;
        private Queue<string> BufferedLines;

        public PeekableStreamReaderAdapter(StreamReader underlying)
        {
            Underlying = underlying;
            BufferedLines = new Queue<string>();
        }

        public string PeekLine()
        {
            string line = Underlying.ReadLine();
            if (line == null)
                return null;
            BufferedLines.Enqueue(line);
            return line;
        }


        public string ReadLine()
        {
            if (BufferedLines.Count > 0)
                return BufferedLines.Dequeue();
            return Underlying.ReadLine();
        }
    }

这篇关于读从一个StreamReader线不会消耗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆