Reputation: 854
I'm trying to write an external merge sort, but it appears that I can't create a second DataInputStream for a file, if I already closed the first one. For example:
public class test {
private static DataInputStream createInputStream(RandomAccessFile f)
throws FileNotFoundException, IOException {
return new DataInputStream(new BufferedInputStream(new FileInputStream(
f.getFD())));
}
private static int readInt(RandomAccessFile file) throws IOException{
DataInputStream istream = createInputStream(file);
int i = istream.readInt();
istream.close();
return i;
}
public static void main(String[] args) throws IOException{
RandomAccessFile file = new RandomAccessFile(args[0], "rw");
for(int j = 0; j < 10; j++){
System.out.println(readInt(file));
}
}
}
When I run this, I get one number out but then get the following error:
java.io.IOException: Stream Closed
at java.io.FileInputStream.readBytes(Native Method)
at java.io.FileInputStream.read(FileInputStream.java:255)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:246)
at java.io.BufferedInputStream.read(BufferedInputStream.java:265)
at java.io.DataInputStream.readInt(DataInputStream.java:387)
at uk.ac.cam.av429.fjava.tick0.test.readInt(test.java:19)
at uk.ac.cam.av429.fjava.tick0.test.main(test.java:26)
How can I create multiple independent streams for a file or do I have to use a single one?
Upvotes: 0
Views: 131
Reputation: 180113
The exception message is a bit misleading. In all likelihood, the problem is that when you close the first stream, it results in the underlying RandomAccessFile
being closed -- or at least its underlying native resources.
Alternatively it's also possible that the first stream consumes all the data from the current position of the RAF to its end, so that there is nothing left to read. It would do this on account of your insertion of a BufferedInputStream
into the nest of streams -- the BIS should be expected to read ahead to fill its buffer, and when you close it, the buffered data are lost.
In any case, you ought not to be going about it this way. Instead of creating a new stream each time, create one stream and re-use it. Just read each subsequent piece of data from the same stream.
Upvotes: 1