问题描述
我正在处理一项任务,并且在代码审查方面遇到了一个问题——“我们是否需要确保在这里使用输入流?”
public void processInputStream(final DataInputStream dataInputStream,final OutputStream output) {
try {
// doing something with dataInputStream!!
} catch (IOException e) {
// doing something with IOException
}
}
我有几个问题 -
#1 我假设如果 InputStream 处理被中断,那么我的 catch 块将被触发。 那是对的吗?如果是这样,是否不需要确保流已被消耗?
#2 在这种情况下,我如何检查 InputStream 是否已被消耗?
谢谢
更新 -
处理我的 InputStream 的一部分涉及使用 -
copyInputStreamToFile(..)
他们的文档说 -
将字节从 InputStream 源复制到文件目标。如果目录不存在,则将创建到目的地的目录。如果目标已经存在,将被覆盖。源流已关闭。有关不关闭输入流的方法,请参阅 copyToFile(InputStream,File)。
这是否意味着给定源流已关闭,那么这包括检查 InputStream 是否已被消耗?
解决方法
您可以使用此方法检查 InputStream 是否已耗尽:
package example;
import java.io.IOException;
import java.io.InputStream;
public class SO {
public static boolean isExhausted(InputStream in) throws IOException {
final boolean exhausted;
if (in.markSupported()) {
in.mark(1);
exhausted = in.read() == -1;
in.reset();
} else {
throw new IllegalStateException("mark is not supported on this inputstream");
}
return exhausted;
}
}
请注意,这只适用于 InputStream 支持标记和重置方法 (in.markSupported())
,这成功了!
private void consumeQuietly(final InputStream inputStream) {
try (OutputStream out = NullOutputStream.NULL_OUTPUT_STREAM) {
IOUtils.copy(inputStream,out);
} catch (IOException ioException) {
// Log something!!
}
}
,
s = df.set_index([df['ID'],df.groupby('ID').cumcount()]).unstack(1)
df1 = pd.concat([s['class'],s['imp']],axis=0).sort_index().fillna('')
print(df1)
idx 0 1 2
ID
111 merc humvee bmw
111 1 2 3
222 vw bmw
222 1 2
333 merc
333 1
您可以使用 public void processInputStream(final DataInputStream dataInputStream,final OutputStream output)
{
try
{
// doing something with dataInputStream!!
}
catch (InterruptedException ie)
{
// doing something with InterruptedException
}
catch (IOException ioe)
{
// doing something with IOException
}
}
方法来确定输入流是否被消耗。