JAVA FileArray class Design a class that has a static method named writeArray. T
ID: 3826866 • Letter: J
Question
JAVA
FileArray 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.
Explanation / Answer
Hi, Please find my implementation.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
public class FileArray {
public static void writeArray(String file, int []arr) throws FileNotFoundException{
PrintWriter out = new PrintWriter(new File(file));
for(int i=0; i<arr.length; i++)
out.write(Integer.toString(arr[i])+" ");
out.close();
}
public static void readArray(String file, int []arr) throws FileNotFoundException{
Scanner sc = new Scanner(new File(file));
int i = 0;
while(sc.hasNextInt()){
arr[i] = sc.nextInt();
i++;
}
sc.close();
}
public static void main(String[] args) throws FileNotFoundException {
int arr[] = {5,3,2,1,11,24,78,98};
writeArray("int_data.txt", arr);
System.out.println(Arrays.toString(arr));
readArray("int_data.txt", arr);
System.out.println(Arrays.toString(arr));
}
}
/*
Sample run:
[5, 3, 2, 1, 11, 24, 78, 98]
[5, 3, 2, 1, 11, 24, 78, 98]
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.