本文介绍了是否有一个类在Java中公开了一个无缓冲的readLine方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在清理工作中的一些代码库,其中一个较旧的类用于读写数据。此数据是US-ASCII编码字符串和二进制编码基元的混合。

I'm cleaning up some chunks of our codebase at work, and one of the older classes is used to read and write data. This data is a mixture of US-ASCII encoded Strings and binary encoded primitives.

当前实现使用,但正如您在文档中看到的那样, readLine()方法是由于与将字节转换为字符相关的问题而弃用。虽然这个编码问题并没有真正为我们提供,但是弃用是一个问题,因为它已经无法在某些版本的OpenJDK 7上运行,并且弃用意味着它可以在将来完全删除。 官方替代方案是从,但由于BufferedReader无法真正处理二进制编码的原语,因此我们无法与DataInputStream完全交换。

The current implementation uses DataInputStream, but as you can see in the documentation the readLine() method is deprecated because of an issue related to converting bytes to characters. While this encoding issue hasn't really popped up for us, the deprecation is an issue since it already doesn't work on some version of OpenJDK 7 and deprecation means that it could be removed entirely in the future. The "official" alternative is to use readLine from BufferedReader, but we can't do a complete swap-out with DataInputStream since BufferedReader can't really handle the binary encoded primitives.

混合这两个类的问题是,当BufferedReader缓冲流时,它会使流标记前进。这意味着从DataInputStream对 readDouble()等方法的后续调用将失败,并且IOExceptions或EOFExceptions因为流标记的实际位置不在应该的位置应用程序逻辑的上下文。

The problem with "mixing" these two classes is that when the BufferedReader buffers off the stream, it advances the stream marker. This means that subsequent calls to methods like readDouble() from DataInputStream will fail with IOExceptions or EOFExceptions since the real location of the stream marker isn't where it "should" be in the context of the application logic.

我查了一些hacky mark() / reset()策略但有时流是由FileInputStream支持的,它不支持 mark() / reset()

I looked in to some sort of hacky mark()/reset() strategy but sometimes the stream is backed by a FileInputStream, which doesn't support mark()/reset().

在更改我们的数据协议之外,将原语写为字符或编写我自己的<$ c实现$ c> readLine()(令人惊讶的是非常重要),有没有办法实现这一目标?我甚至愿意考虑一个外部库。

Outside of changing our data protocol to write out the primitives as characters or writing my own implementation of readLine() (which is surprisingly non-trivial), is there any way to achieve this? I'd even be willing to consider an external library at this point.

推荐答案

我认为你应该创建一个自定义子类 DataInputStream ,它添加一个 readLine 类似的方法,它可以满足您的需要。 (你甚至可以覆盖现有的 readLine()方法。)

I think that you should create a custom subclass of DataInputStream that adds a readLine-like method that behaves how you need it to. (You could even override the existingreadLine() method.)

是的,有效的实现是非常重要的,但是如果你将自定义类堆叠在 BufferedInputStream 之上,你可能会得到一个天真的实现。

Yes, an efficient implementation is non-trivial, but you could probably get away with a naive implementation if you stack your custom class on top of a BufferedInputStream.

这篇关于是否有一个类在Java中公开了一个无缓冲的readLine方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 01:30