Search code examples
javaarrayspersistencenio

NIO Persistent Array : Java


I've been assigned the task of creating a NIO Persistent Array in my "Advanced" Java course. This question is not so much 'how' to do this, but 'what' is implied by "NIO Persistent". This is a new concept to me; so far I understand that basically this just means that instead of dynamically storing information in the typical array in code, you store the array's information on-disk in the form of bytes in pre-determined sized blocks. What I'm confused about is how you get from the information you're trying to store to bytes, and then how do you write those bytes to a file via Java's NIO?

TL;DR - Can someone explain a Java NIO Persistent Array in a nutshell? How should I go about constructing one from the ground up?

Thanks for any comments you have in advance!

EDIT: Here is the assignment description, word for word:

Objective

Become familiar with Java's NIO API.

Requirements

Use Java's NIO to create a PersistentArray class. The class should support the following methods:

static void create(String fileName, int bufferSize) - creates an empty persistent array

static void delete(String fileName) - deletes the persistent array

PersistentArray open(String fileName) - opens the file associated with the persistent array and prepares the persistent array for gets and puts.

void put(int bufferID, Buffer buffer) - Stores the buffer at the bufferID's location (note that the buffer size must be the same as the size used when creating the array).

Buffer get(int bufferID) - given the buffer ID, retrieve the buffer previously stored at the location associated with bufferID.

int getNextID() - return one beyond the maximum ID ever used for storing a buffer .

void close() - close the file associated with the persistent array

Also, create a JUnit test showing that all methods behave as expected.

Review your work with the instructor.


Solution

  • What:
    There is no such thing like "NIO persistent array". The instructor wants you to get acquainted with the NIO API (since it's better and faster than old IO API).

    Now in context to the assignment, you need to implement this class which adheres to the spec specified by the instructor. No fancy stuff, just implement a class which "persists" data (an array in your case) to a file using nio.

    This writeup might help you. File I/O: old I/O or NIO. Which is better?

    TL;DR: There is no special meaning to NIO persistence. Just create an array which is not in memory, but also persists its content using NIO.

    How:
    Now, it can be implemented in many ways, Peter's answer is pretty good where is has recommended to use a RandomAccessFile.