Question: Java Random Access files Create a program that reads and stores memos in a RandomAccessFile. To be able to read and write memos in a

Java Random Access files

Create a program that reads and stores memos in a RandomAccessFile. To be able to read and write memos in a random access file, the topic, date stamp and message should each have a fixed size.

First, complete the code for the class MemoPad. You will write the tester program in the next problem.

public class MemoPad { public MemoPad() { file = null; }

public void open(String filename) throws IOException { . . . }

/** Gets the number of memos in the file. @return the number of memos */ public int size() throws IOException { . . . }

public void close() throws IOException { if (file != null) file.close(); file = null; } /** Reads a memo record. The values of the last record read can be obtained with the getTopic, getDateStamp and getMessage methods. @param n the index of the memo in the file */ public void read(int n) throws IOException { file.seek(. . .); byte[] topic = new byte[MAX_CHARS_TOPIC]; byte[] date = new byte[MAX_CHARS_DATE]; byte[] message = new byte[MAX_CHARS_MSG]; /* Read the topic, date and message from the file (use the method "read(byte[])". Then, convert the byte arrays to strings and store them in the variables currentTopic, currentDateStamp and currentMessage */ }

public String getTopic() { return currentTopic; // returns the topic of the last memo read } public String getDateStamp() { return currentDateStamp; } public String getMessage() { return currentMessage; } public void write(int n, String topic, String dateStamp, String message) throws IOException { file.seek(. . .);

file.writeBytes(. . .); // "topic" should have a fixed size file.writeBytes(. . .); // "dateStamp" should have a fixed size file.writeBytes(. . .); // "message" should have a fixed size }

/** Adds white spaces to a string or cuts the string, so the string has a length of exactly "size". @param str the input string @param size the desired size @return the new string */ private String padOrTrim(String str, int size) { if (str.length() < size) { String pad = ""; for (int i = str.length(); i < size; i++) pad = pad + " "; return str + pad; } else return str.substring(0, size); }

private RandomAccessFile file; private String currentTopic; private String currentDateStamp; private String currentMessage;

public static final int MAX_CHARS_TOPIC = 25; public static final int MAX_CHARS_DATE = 40; public static final int MAX_CHARS_MSG = 250; public static final int RECORD_SIZE = MAX_CHARS_TOPIC + MAX_CHARS_DATE + MAX_CHARS_MSG; } What is the complete code for this class?

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!