javafilestreammergesortexternal-sorting

Switching between file paths in Java


I am writing a mergesort for an externalsort, which reads 2 chunks of data at a time from a file A, merges them into a larger chunk, and writes it to a file B. After this, I need to then read 2 of these increased chunks at a time from file B, merge them into 1 larger chunk, and write this to file A. This switching goes on until all the data counts as 1 chunk at the end.

I have tried swapping the identifiers around like this after each iteration:

RandomAccessFile temp = fileA;
    fileA = fileB;
    fileB = temp;

This requires, that I update the BufferedInput and BufferedOutputStreams with the new file directory names and construct them each time.

I have a limited amount of RAM, so I cannot keep creating new objects unless I have to. Is there a better way to switch the target file and source file each iteration?


Solution

  • A simple generic Swapable class should allow you to swap between two objects.

    class Swapable<T> {
        final T a;
        final T b;
        boolean useA = true;
    
        Swapable(T a, T b) {
            this.a = a;
            this.b = b;
        }
    
        T get() {
            return useA ? a : b;
        }
    
        void swap() {
            useA = !useA;
        }
    }
    

    Create your two RandomAccessFiles and install them in a Swapable. Use the get method to get the current file. Use the swap method to switch between them.