10 Files & Serialization

Files, Streams, and Serialization

Objective

  • Read and write text files.
  • Work with object serialization.

Summary

  1. All data in and out of a computer is treated by the system as a stream of data. Also, the term stream refers to ordered data that is read from or written to a file. Each file is viewed as a sequential stream of bytes.
  2. File streams can be used to input and output data as either characters or bytes.
  3. Streams that input and output characters to files are known as character-based streams, storing data as a sequence of characters. Streams that input and output bytes to files are known as byte-based streams, storing data in its binary format.
  4. Files that are created using byte-based streams are referred to as binary files. Files that are created using character-based streams are referred to as text files.
  5. Object serialization is the ability to read an entire object from or write an entire object to a file.
  6. A serialized object is represented as a sequence of bytes that includes the object’s data and its type information.
  7. After a serialized object has been written into a file, it can be read from the file and deserialized to recreate the object in memory.
  8. Objects of classes that implement interface Serializable can be serialized and de-serialized with ObjectOutputStream and ObjectInputStream.

Exercise 1*

Text Files: Working with the Formatter Class

  1. Create a new project and add the following class to it. Run the application and type any text that you would like to save. When you finish typing, press <Ctrl+Z> or <Ctrl+D> to end the input, then open the file output.txt and check its content.

    FormatterDemo.java
    import java.io.File;
    import java.io.IOException;
    import java.util.Formatter;
    import java.util.Scanner;
     
    public class FormatterDemo {
      public static void main(String[] args) {
        Formatter output = null;
        Scanner scanner = new Scanner(System.in);
     
        try {
          // output = new Formatter("output.txt");
          output = new Formatter(new File("output.txt"));
        } catch (IOException ioe) {
          System.out.println("File could not be opened/created. An exception occurred.\n" +
                            ioe);
        }
     
        if (output != null) {
          System.out.println(
              "Enter the data to be saved. When done, press <Ctrl+Z>/<Ctrl+D>:");
     
          while (scanner.hasNext()) {
            String line = scanner.nextLine();
            output.format("%s%n", line);
          }
          output.close();
        }
        scanner.close();
      }
    }
  2. Run the program and enter your name and then finish the input, then open the file and see what you typed. Close the file, run the program once more and then type CMPS 251 Lab and then terminate your program. Does it replace the previous content or is it added at the end of the file?

  3. How can you add new content to an existing file (append) without replacing the old content?

Exercise 2*

Text Files: Working with the Formatter and FileWriter Classes

  1. Add the following class to your project. Run the application and type any text that you would like to save. When you finish typing, press <Ctrl+Z> or <Ctrl+D> to end the input, then open the file output.txt and check its content.

    FileWriterDemo.java
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.Formatter;
    import java.util.Scanner;
     
    public class FileWriterDemo {
      public static void main(String[] args) {
        FileWriter writer = null;
        Formatter output = null;
        Scanner scanner = new Scanner(System.in);
     
        try {
          writer = new FileWriter("output.txt", true);
          output = new Formatter(writer);
        } catch (IOException ioe) {
          System.out.println("File could not be opened/created. An exception occurred.\n" +
                            ioe);
        }
     
        if (output != null) {
          System.out.println(
              "Enter data to be saved. When done, press <Ctrl+Z>/<Ctrl+D>:");
     
          while (scanner.hasNext()) {
            String line = scanner.nextLine();
            output.format("%s%n", line);
          }
          output.close();
        }
        scanner.close();
      }
    }
  2. Run the program once more and enter your name and then finish the input. Open the file and see what you typed. Does it replace the previous content, or it is added at the end of the file?

  3. What is the purpose of the true keyword when provided as a second argument in the FileWriter constructor?

  4. What happens to the file content if you do not provide this second argument?

Exercise 3*

Object Serialization

  1. Add the following two classes to your project then run the app and examine the output

    ObjectSerialization.java
    import java.io.EOFException;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
     
    public class ObjectSerialization {
      public static void main(String[] args) {
        try {
          ObjectOutputStream output =
              new ObjectOutputStream(new FileOutputStream("persons.dat"));
          Person person1 = new Person("John");
          Person person2 = new Person("Jane");
     
          // Saving objects
          output.writeObject(person1);
          output.writeObject(person2);
          output.close();
     
          // Reading objects
          ObjectInputStream input =
              new ObjectInputStream(new FileInputStream("persons.dat"));
          Object object;
          Person person;
          while ((object = input.readObject()) != null) {
            person = (Person)object;
            System.out.println(person.getName());
          }
          input.close();
        } catch (EOFException eof) {
          System.out.println("Reached end of file.");
        } catch (IOException | ClassNotFoundException exception) {
          System.out.println(exception.getStackTrace());
        }
      }
    }
    Person.java
    public class Person {
      private String name;
      public String getName() { return name; }
      public void setName(String name) { this.name = name; }
      public Person(String name) { this.name = name; }
    }
  2. Did you obtain the names of the two created Person objects? Were they saved? If not, why?

  3. Let the Person class implement the Serializable interface and then run the application again. Compare the output with that of the previous run. What is your conclusion?

Exercise 4

The names.txt file contains a list of names along with their gender and origin:

Name	Gender	Origin
Khalid	M	Arabic
Alia	F	Hindi
Fatima	F	Arabic
Sara	F	Hebrew
Omar	M	Arabic
Eman	F	Arabic
Farah	F	Hebrew
Ali	M	Arabic
Ahmed	M	Arabic
Omnia	F	Arabic
  1. Write an application that opens the file and lists the female names of Arabic origin. Your listing should only show the name and gender; do not show the origin as it is that same for all the filtered output.
  2. Properly format your output using a tabular layout.
  3. Send a copy of the output to a text file called arabic-names.txt.

Exercise 5

  1. Modify the Person class of Exercise 3 by adding two more fields: id: int and salary: double. Add setters/getters and modify the constructor to have three parameters to initialize all fields.
  2. Write a new application that asks the user to enter a person’s information, create a Person instance, and then save it in a file of objects named employees.data. The program continues to accept data and sends them as objects to the above file. The program terminates when the user enters a negative id.
  3. Write another application that opens the employees.dat file and loads its contents in an ArrayList of type Person.
  4. Write a method called getPerson(int searchId) that searches the above list for a person with id equals to the searchId. If found the function returns that Person instance, and, if not found the method returns null.
  5. Test the getPerson() method by printing the salary for the search person, if found.

Exercise 6+

  1. Write a program to read students’ data that includes their name: String and three grades: double. Your program should ask the user at the beginning to input how many students they would like to enter, then keep reading the records while saving them to a file called students.txt.
  2. Write a program to read students’ data from the file saved previously, and display each students’ name and average on a separate line.

Exercise 7+

  1. Create a text file, employees.txt, that contains data about employees as follows:

    IDNameSalary
    234Sara4500.00
    987Khaled7345.12
    997Nadim1267.00
    523Noora8230.00
  2. Create an Employee class that has three data members: id: int, name: String, and salary: double. Add a constructor and setter/getter methods.

  3. Write a program that reads data from the file employees.txt to an ArrayList of Employee, then save this ArrayList to a binary fine called employee.dat, as a single object.

  4. Write another program to retrieve the data saved in the file employee.dat, and display the employee records on the screen.