gpt4 book ai didi

java - 试用资源和 System.in

转载 作者:搜寻专家 更新时间:2023-11-01 03:05:49 25 4
gpt4 key购买 nike

好吧,这可能不是最好的问题,但我一直坚持下去,无法在网上找到答案。

此代码不会第二次从标准输入读取:

try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in)))
{
input = br.readLine();
}
catch (final Exception e)
{
System.err.println("Read from STDIN failed: " + e.getMessage());
}
// do some processing
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in)))
{
input = br.readLine();
}
catch (final Exception e)
{
System.err.println("Read from STDIN failed: " + e.getMessage());
}

我知道 java 的 try-with-resources 会递归地关闭链中的所有流,因此在第一次读取 System.in 后关闭。有什么好的解决方法吗?还是我真的应该自己处理流关闭?

更新:我试图自己处理关闭的流(即 java6 风格)。这是一个 code如果有人感兴趣。但我注意到这种链关闭行为不是来自 try-with-resources,而是来自关闭方法的实现。所以我没有从那次尝试中赢得任何东西。

我选择 fge 的解决方案,因为它是最冗长的解决方案。它直接对我有用。

总而言之,我觉得很奇怪,java 没有开箱即用的解决方案,因为存在不应该关闭的系统流。

最佳答案

一种解决方法是创建一个自定义 InputStream 类,该类将委托(delegate)给另一个类,但它在自身关闭时不会 .close() 它。如:

public class ForwardingInputStream
extends InputStream
{
private final InputStream in;
private final boolean closeWrapped;

public ForwardingInputStream(final InputStream in, final boolean closeWrapped)
{
this.in = in;
this.closeWrapped = closeWrapped;
}

public ForwardingInputStream(final InputStream in)
{
this(in, false);
}

@Override
public int read()
throws IOException
{
return in.read();
}

@Override
public int read(final byte[] b)
throws IOException
{
return in.read(b);
}

@Override
public int read(final byte[] b, final int off, final int len)
throws IOException
{
return in.read(b, off, len);
}

@Override
public long skip(final long n)
throws IOException
{
return in.skip(n);
}

@Override
public int available()
throws IOException
{
return in.available();
}

@Override
public void close()
throws IOException
{
if (closeWrapped)
in.close();
}

@Override
public synchronized void mark(final int readlimit)
{
in.mark(readlimit);
}

@Override
public synchronized void reset()
throws IOException
{
in.reset();
}

@Override
public boolean markSupported()
{
return in.markSupported();
}
}

请注意,在您的情况下,一个可能更简单的解决方案是扩展 InputStreamReader,因为该类不是 final 并且只是覆盖 .close().

关于java - 试用资源和 System.in,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23041258/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com