Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Design a class that has a static method named writeArray. The method should take

ID: 3650591 • Letter: D

Question

Design a class that has a static method named writeArray. The method should take two arguments: the name of a file and a reference to an int array. The file should be opened, data should be read from the file and stored i nthe array, and then the file should be closed. Demonstrate both methods in a program.

***In both methods, write the data out to the console as well as the file operations. The file name should be data.
***

Explanation / Answer

import java.io.IOException; import java.io.RandomAccessFile; /** * This class represents a list of strings saved persistently to a file, along * with an index that allows random access to any string in the list. The static * method writeWords() creates such an indexed list in a file. The class * demostrates the use of java.io.RandomAccessFile */ public class WordList { // This is a simple test method public static void main(String args[]) throws IOException { // Write command line arguments to a WordList file named "words.data" writeWords("words.data", args); // Now create a WordList based on that file WordList list = new WordList("words.data"); // And iterate through the elements of the list backward // This would be very inefficient to with sequential-access streams for (int i = list.size() - 1; i >= 0; i--) System.out.println(list.get(i)); // Tell the list we're done with it. list.close(); } // This static method creates a WordList file public static void writeWords(String filename, String[] words) throws IOException { // Open the file for read/write access ("rw"). We only need to write, // but have to request read access as well RandomAccessFile f = new RandomAccessFile(filename, "rw"); // This array will hold the positions of each word in the file long wordPositions[] = new long[words.length]; // Reserve space at the start of the file for the wordPositions array // and the length of that array. 4 bytes for length plus 8 bytes for // each long value in the array. f.seek(4L + (8 * words.length)); // Now, loop through the words and write them out to the file, // recording the start position of each word. Note that the // text is written in the UTF-8 encoding, which uses 1, 2, or 3 bytes // per character, so we can't assume that the string length equals // the string size on the disk. Also note that the writeUTF() method // records the length of the string so it can be read by readUTF(). for (int i = 0; i
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote