Ask Question

Design a class FileArray 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 static method in the class FileArray 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 written into the array, and then the file should be closed.

+5
Answers (1)
  1. 17 March, 12:43
    0
    import java. io. DataInputStream;

    import java. io. DataOutputStream;

    import java. io. FileInputStream;

    import java. io. FileOutputStream;

    import java. io. IOException;

    public class FileArray

    {

    public static void writeArray (String fileName, int[] array) throws IOException

    {

    FileOutputStream fstream = new FileOutputStream (fileName);

    DataOutputStream outputFile = new DataOutputStream (fstream);

    for (int index = 0; index < array. length; index++)

    {

    outputFile. writeInt (array[index]);

    }

    outputFile. close ();

    }

    public static void readArray (String fileName, int[] array) throws IOException

    {

    FileInputStream fstream = new FileInputStream (fileName);

    DataInputStream inputFile = new DataInputStream (fstream);

    for (int index = 0; index < array. length; index++)

    {

    array[index] = inputFile. readInt ();

    }

    inputFile. close ();

    }

    }

    Explanation:

    The above code has the Class named FileArray and Static method as writeArry. and it takes String fileName, int[] array as arguments. String fileName is for the name of the file and int[] array for the reference to the int array. OutputStream and InputStream are abstract classes used to read byte streams to read and write binary data. Content of the file is written to the file.

    Second static method of FileArray is wriiten as readArray and it also takes two arguments similar to static method writeArray. In this data is read from the file and written into array.
Know the Answer?
Not Sure About the Answer?
Find an answer to your question 👍 “Design a class FileArray that has a static method named writeArray. The method should take two arguments: the name of a file and a ...” in 📗 Computers & Technology if the answers seem to be not correct or there’s no answer. Try a smart search to find answers to similar questions.
Search for Other Answers