Question

I'm reading numbers from a file in order to perform a merge sort. The merge sort must be performed as an external sort as it is a large list of numbers and there is very little main memory available. I have a working implementation, it uses the BufferedOutputStream to speed up output, and I want to do the same for the input stream. However, the input must be read from two different places to perform the merge.

Essentially, if I have:

RandomAccessFile File = new RandomAccessFile("File.dat", "rw");
BufferedInputStream Buffer = new BufferedInputStream(
   new FileInputStream(File.getFD()));
DataInputStream InputStream = new DataInputStream(Buffer);

And I read some integers using InputStream.readInt(), but also want to use File.seek(n) to access other parts of the file, how do I know when the File will next be called for more data and therefore seek back before it is asked for more data. Alternatively, is it possible to have two RandomAccessFiles, for the same underlying file?

Was it helpful?

Solution

For anyone else who needs to do the same thing, here's an example of reading from a stream using two different bufferedInputStreams and RandomAccessFiles:

        RandomAccessFile FileA = new RandomAccessFile("File.dat", "rw");
        System.out.println("Writing 100");
        for (int i = 0; i < 100; i++) {
            FileA.writeInt(i);
        }
        FileA = new RandomAccessFile("File.dat", "r");
        RandomAccessFile FileB = new RandomAccessFile("File.dat", "r");


        FileA.seek(0);
        DataInputStream InputStreamA = new DataInputStream(new BufferedInputStream(
                new FileInputStream(FileA.getFD())));

        FileB.seek(0);
        DataInputStream InputStreamB = new DataInputStream(new BufferedInputStream(
                new FileInputStream(FileB.getFD())));


        System.out.println("Read A");
        for (int i = 0; i < 10; i++) {
            System.out.println(InputStreamA.readInt());
        }

        System.out.println("Read B");
        for (int i = 0; i < 10; i++) {
            System.out.println(InputStreamB.readInt());
        }

        System.out.println("Run A");
        for (int i = 0; i < 10; i++) {
            System.out.println(InputStreamA.readInt());
        }

        System.out.println("Run B");
        for (int i = 0; i < 10; i++) {
            System.out.println(InputStreamB.readInt());
        }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top