您正在使用茶匙和铲子从孔中清除污垢。
我知道流是具体的,从它读取将消耗它的输入,无论它是从哪里完成的
正确的。茶匙和铲子都可以从孔中清除污垢。如果您正在异步(即同时)清除污垢,您可能会为谁拥有什么污垢而争吵 - 所以使用并发构造来提供互斥访问。如果访问不是并发的,换句话说......
1)从孔中移出一或多茶匙污垢
2)从孔中移出一或多铲污垢
3)从孔中移出一或多茶匙污垢
...
没问题。茶匙和铲子都可以去除污垢。但是一旦污垢被去除,它就会被去除,它们不会得到同样的污垢。希望这可以帮助。让我们开始铲,我会用茶匙。:)
正如快速反应所发现的那样,在共享流时要非常小心,尤其是缓冲的阅读器,因为它们可以从流中吞噬比他们需要的更多的字节,所以当你回到你的其他输入流(或阅读器)时,它可能看起来像一大堆字节已被跳过。
证明您可以从相同的输入流中读取:
import java.io.*;
public class w {
public static void main(String[] args) throws Exception {
InputStream input = new FileInputStream("myfile.txt");
DataInputStream b = new DataInputStream(input);
int data, count = 0;
// read first 20 characters with DataInputStream
while ((data = b.read()) != -1 && ++count < 20) {
System.out.print((char) data);
}
// if prematurely interrupted because of count
// then spit out last char grabbed
if (data != -1)
System.out.print((char) data);
// read remainder of file with underlying InputStream
while ((data = input.read()) != -1) {
System.out.print((char) data);
}
b.close();
}
}
输入文件:
hello OP
this is
a file
with some basic text
to see how this
works when moving dirt
from a hole with a teaspoon
and a shovel
输出:
hello OP
this is
a file
with some basic text
to see how this
works when moving dirt
from a hole with a teaspoon
and a shovel
证明 BufferedReader 不能保证工作,因为它会从流中吞噬大量字符:
import java.io.*;
public class w {
public static void main(String[] args) throws Exception {
InputStream input = new FileInputStream("myfile.txt");
BufferedReader b = new BufferedReader(new InputStreamReader(input));
// read three lines with BufferedReader
String line;
for (int i = 0; (line = b.readLine()) != null && i < 3; ++i) {
System.out.println(line);
}
// read remainder of file with underlying InputStream
int data;
while ((data = input.read()) != -1) {
System.out.print((char) data);
}
b.close();
}
}
输入文件(同上):
hello OP
this is
a file
with some basic text
to see how this
works when moving dirt
from a hole with a teaspoon
and a shovel
输出:
hello OP
this is
a file