【发布时间】:2013-08-28 23:26:43
【问题描述】:
我在这里想要实现的是通过使用 apache-commons 打印 InputStream 的内容来获得更多的调试输出。好像我在这个过程中改变了流本身。
InputStream is = getClass().getResourceAsStream("file.txt");
IOUtils.copy(is, System.out); //Happily Prints out contents of file.txt
IOUtils.copy(is, System.out); //Doesn't print anything
为什么使用 IOUtils 复制流会改变流?我尝试克隆流,然后将其打印出来,但仍然没有运气。我尝试从 apache commons 克隆 CloseShieldInputStream。
InputStream is = getClass().getResourceAsStream("file.txt");
CloseShieldInputStream csis = new CloseShieldInputStream(is);
IOUtils.copy(csis, System.out);//Happily Prints out contents of file.txt
IOUtils.copy(is, System.out);//Still Doesn't print anything
有人可以解释为什么即使源流丢失了其内容,他们也将这些方法称为“复制”?如何打印流而不担心丢失其内容?
编辑:
这段代码(除了流被初始化的地方)在一个 3rd-Party 库中非常深入,并且流在经过几个方法后被传递。很难弄清楚流在哪里被初始化,并在那里显示然后重新初始化。我正在拼命地尝试显示这个流并且仍然保持不变。
【问题讨论】:
-
你不能。一般来说,
InputStream只能读取一次。如果您想再次使用其内容,则需要重新打开该流。
标签: java stream inputstream apache-commons