java 读取流中的第一行并将其从流中删除

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3360863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 01:29:18  来源:igfitidea点击:

Read the first line in a stream and remove it from the stream

java

提问by Stijn Vanpoucke

I have 2 classes who must read an InputStream, the first one should only interpret the first line of the stream BUT the first line should be removed from the stream so that class B can interpret everything after the first line. Which doesn't work when I pass my InputStreamto a BufferedReaderand do a readLine().

我有 2 个必须读取 的类InputStream,第一个类应该只解释流的第一行,但是应该从流中删除第一行,以便 B 类可以解释第一行之后的所有内容。当我将 my 传递InputStream给 aBufferedReader并执行 a时,这不起作用readLine()

I know I could do a read on the stream until I've encountered a \b but maybe a more proper solution exists to do the job?

我知道在遇到 \b 之前我可以读取流,但也许存在更合适的解决方案来完成这项工作?

// Reads the first line from the stream and everything else
public String retrieveFileNameFromTheFirstLineInInputStream(InputStream in) throws IOException {
    InputStreamReader isReader = new InputStreamReader(in);
    BufferedReader reader = new BufferedReader(isReader);
    return reader.readLine();
}

采纳答案by Mot

You can't removesomething from an InputStream, you just can readfrom it. Don't use the BufferedReaderto read the line, because it surely will read much more than the first line from the InputStreamReader(to fill its buffer) which itself reads from the InputStream.

您无法从 中删除某些内容InputStream,您只能从中读取。不要使用BufferedReader来读取该行,因为它肯定会比InputStreamReaderInputStream.

I'd suggest to read using the InputStreamReaderuntil the end of the line is reached, then pass the InputStreaminstance to your code which should read it.

我建议使用 阅读InputStreamReader直到到达行尾,然后将InputStream实例传递给您应该阅读它的代码。

BTW, you always should specify the encoding used by the InputStreamReader, otherwise the system encoding will be used to convert the bytes from the InputStreamto characters which can differ on different machines.

顺便说一句,您应该始终指定 使用的编码InputStreamReader,否则系统编码将用于将字节从 转换为InputStream不同机器上可能不同的字符。

回答by dfrankow

I believe even InputStreamReader can buffer input, so Mike L's answer can miss input.

我相信即使 InputStreamReader 也可以缓冲输入,所以 Mike L 的回答可能会错过输入。

It's awkward, but you could use ReaderInputStreamfrom Apache commons-io. So:

这很尴尬,但您可以使用Apache commons-io 中的ReaderInputStream。所以:

BufferedReader reader = new BufferedReader(
    new InputStreamReader(in));
String firstLine = reader.readLine();
InputStream in2 = new ReaderInputStream(reader);
// continue with in2 ..