从流读取器读取一行而不消耗?
有没有办法提前读取一行来测试下一行是否包含特定标签数据?
我正在处理具有开始标记但没有结束标记的格式。
我想读取一行,将其添加到一个结构中,然后测试下面的行,以确保它不是一个新的“节点”,如果它不是关闭该结构,则继续添加,并使一个新的成为
唯一的解决方案我能想到的是让两个流读取器同时进行,沿着锁定步骤有点令人沮丧,但这似乎很浪费(如果它甚至可以工作)
我需要类似 peek 但 peekline 的东西
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
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)
i need something like peek but peekline
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
问题是底层流甚至可能不可查找。 如果您查看流读取器实现,它使用缓冲区,因此即使流不可查找,它也可以实现 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:
您可以存储访问 StreamReader.BaseStream.Position 的位置,然后读取下一行,进行测试,然后在读取该行之前查找到该位置:
这是大量查找和重新读取相同的行。 使用一些逻辑,您也许能够完全避免这种情况 - 例如,当您看到一个新标签开始时,关闭现有结构并开始一个新结构 - 这是一个基本算法:
You could store the position accessing StreamReader.BaseStream.Position, then read the line next line, do your test, then seek to the position before you read the line:
This is a lot of seeking and re-reading the same lines. Using some logic, you may be able to avoid this altogether - for instance, when you see a new tag start, close out the existing structure and start a new one - here's a basic algorithm:
为什么有困难? 无论如何,返回下一行。 检查是否是新节点,如果不是,则将其添加到结构体中。 如果是,则创建一个新结构。
Why the difficulty? Return the next line, regardless. Check if it is a new node, if not, add it to the struct. If it is, create a new struct.
这是我到目前为止所做的。 我更多地采用了分割路线,而不是逐行路线的流阅读器。
我确信有一些地方正在努力变得更加优雅,但目前看来它正在发挥作用。
请让我知道你在想什么
Here is what i go so far. I went more of the split route than the streamreader line by line route.
I'm sure there are a few places that are dieing to be more elegant but for right now it seems to be working.
Please let me know what you think