java from control structures through objects 6th\' Programming challenge number
ID: 3822624 • 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.util.Arrays;
import java.io.BufferedWriter;
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.IOException;
class WriteToFile{
/*Static method to write data to file from Array */
static void writeArray(String filename,int[] array) {
FileWriter fw = null;
BufferedWriter bw = null;
try {
fw = new FileWriter(filename);
bw = new BufferedWriter(fw);
bw.write(Arrays.toString(array));
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bw != null)
bw.close();
if (fw != null)
fw.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
/*Static method to read data from file.
if want to add data to array, import JSON library and uncomment the commented code . */
static void readArray(String filename,int[] array) {
try {
BufferedReader br = new BufferedReader(new FileReader(filename));
String Line;
while ((Line = br.readLine()) != null) {
System.out.println(Line);
}
/* JSONArray jsonArray = (JSONArray) new JSONObject(new JSONTokener("{data:"+Line+"}")).get("data");
for(int i=0; i<jsonArray.length(); i++) {
array[i] = jsonArray.getInt(i);
}
System.out.println(Arrays.toString(array));
*/
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String file = new String("try.txt");
int[] array = new int[] {11,22,33,44,55};
int[] array2 = new int[6];
writeArray(file,array);
readArray(file,array2);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.