java from control structures through objects 6th\' Programming challenge number
ID: 3822597 • Letter: J
Question
java from control structures through objects 6th'
Programming challenge number 6)File Array Class
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 as a binary file, the contents of the array should be written to the file, and then the file should be closed.
Write a second method in the class named readArray. 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 in the array, and then the file should be closed.
Demonstrate both methods in a program, Use comments through the code.
Explanation / Answer
import java.io.*;
public class FileArray
{
public static void writeArray(int[] num, String fileName) throws IOException
{
//Create binary output objects
FileOutputStream fstream = new FileOutputStream(fileName);
DataOutputStream outputFile = new DataOutputStream(fstream);
System.out.println("Writing to the file.");
//Write the array elements to the binary file
for (int i = 0; i < num.length; i++)
outputFile.writeInt(num[i]);
//Close the file
outputFile.close();
System.out.println("Succesfully wrote to the file");
}
public static void readArray(int[] num, String fileName) throws IOException
{
int i = 0;
boolean endOfFile = false;
System.out.println("Reading numbers from the file: ");
//Create binary output objects
FileInputStream fstream = new FileInputStream(fileName);
DataInputStream inputFile = new DataInputStream(fstream);
while (!endOfFile)
{
try
{
num[i] = inputFile.readInt();
i++;
System.out.println(i + " ");
}
catch (EOFException e)
{
endOfFile = true;
}
}
//Close the file
inputFile.close();
System.out.println("Succesfully closed the file.");
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.