13. File Handling

About this Tutorial –

Objectives –

This course is aimed at object-oriented developers (e.g. C++ or C#) who need to transition into Java. It is also aimed at those learning to program for the first time; the course covers the Java programming constructs and APIs quickly, focussing on the differences between Java and other OO languages.

Audience

This training course is aimed at OO developers who need to transition into Java.

Prerequisites

No previous experience in Java programming is required. But any experience you do have in programming will help. Also no experience in eclipse is required. But again any experience you do have with programming development environments will be a valuable.

Contents

The Java course cover these topics and more:

  • Flow Control: Decision making: if and if-else; The switch statement; Looping: for loops; while loops; do-while loops; for-each style loops; Assertionsv
  • Concurrency: Overview of multithreading; Creating new threads; Object locking; Using wait, notify, and notifyAll
  • Collections: Overview of Java SE collection classes; Generics; Using List-based collection classes; Using Set-based collection classes; Using Map-based collection classes; Collection techniques

Exam Preparation

The Java course will help you prepare for these certifications:

  • Oracle Certified Java Associate – Exam 1Z0-803
  • Oracle Certified Java Professional – Exam 1Z0-804

Download Solutions

HTML tutorial


Overview

Estimated Time – 1.5 Hour

Not what you are looking? Try the next tutorial – Accessing Databases using JDBC

Lab 1: Working with files

Lab 1: Working with files
  1. The File Class
    • File represents a file or directory on the file system
      • It doesn’t have any read/write capabilities
    • If you want to read/write a file:
      • Use other classes such as reader/writer classes and streams
      • See later in this chapter
    • Here are some of the methods in the File class:
      • exists(), canRead(), canWrite()
      • getName(), getPath(), getAbsolutePath()
      • Etc…
  2. Useful File Methods – Queries
  3. T13P1

  4. Specifying Directories and File Paths
    • When specifying directory names, you can use a / to separate directories
    • When specifying the name and location of a file, you can use:
      • An absolute path name
      • Or a relative path name
    • If you want to create a File object that represents a file on a remote computer
      • Use the Universal Naming Convention (UNC)
      • E.g. //hostname/folder/subfolder/…
  5. Creating a New Directory
  6. T13P2

  7. Creating a New File

      T13P3

    • Note:
      • File.createNewFile() throws an IOException
      • You must either catch this exception, or propagate it (as above)
  8. Displaying File Info
    public static void demoDisplayingFileInfo() {
     String dirName = "c:/MyNewFolder/MyNewSubFolder/";
     String fileName = "Customers.txt";
     File customersFile = new File(dirName + fileName);
     System.out.printf("\nName:     %s\n", customersFile.getName());
     System.out.printf( "Absolute path: %s\n", customersFile.getAbsolutePath());
     System.out.printf( "Is file?    %b\n", customersFile.isFile());
     System.out.printf( "Is directory? %b\n", customersFile.isDirectory());
     System.out.printf( "Can read?   %b\n", customersFile.canRead());
     System.out.printf( "Can write?   %b\n", customersFile.canWrite());
     System.out.printf( "Length:    %d\n", customersFile
  9. View code file.
  10. T13P4

  11. Displaying Directory Info
    public static void demoDisplayingDirectoryInfo() {
     String dirName = "c:/MyNewFolder/MyNewSubFolder/";
     File dir = new File(dirName);
     if (dir.exists() && dir.isDirectory()) {
      System.out.printf("\nAbsolute path: %s\n", dir.getAbsolutePath());
      System.out.printf( "Is file?    %b\n", dir.isFile());
      System.out.printf( "Is directory? %b\n", dir.isDirectory());
      System.out.printf( "Can read?   %b\n", dir.canRead());
      System.out.printf( "Can write?   %b\n", dir.canWrite());
      System.out.printf( "Length:    %d\n", dir.length());
      System.out.println("Files: ");
      for (String filename : dir.list())
       System.out.println("\t" + filename);
     }
    }
  12. View code file.
  13. T13P5

Lab 2: Text files

Lab 2: Text files
  1. Overview of Text File Output
    • Java provides “writer” classes for writing text files
      • Here are some of the most commonly used classes
      • T13P6

  2. Creating Writer Objects
    • To write text to a file, you will typically create 3 objects arranged in cascading manner, like so:
    • T13P7

    • Example:
      • ReadingWritingTextFiles.java, demoWritingTextFiles()
  3. Overview of Text File Input
    • Java also provides “reader” classes for reading text files
      • Here are some of the most commonly used classes
      • T13P8

  4. Creating Reader Objects
    • To read text from a file, you will typically create 2 objects arranged in cascading manner, like so:
    • T13P9

    • Example:
      • ReadingWritingTextFiles.java, demoReadingTextFiles()
Lab
  1. Reading/writing data to a text file
    • In EmployeePersister, write the readFromTextFile() and writeToTextFile() methods as per the comments in the code, to read/write an Employee to a text file
       @Override
       public Employee readFromTextFile(BufferedReader reader) throws IOException {
        String line = reader.readLine();
        if (line == null) {
         // No Employee data read from file.
         return null;
        }
        
        // Split the line at tab characters, to get at each piece of Employee data separately.
        String[] columns = line.split("\t");
        // Create an Employee object, using data from file.
        return new Employee(columns[0],
           columns[1],
           Double.parseDouble(columns[2]),
           Boolean.parseBoolean(columns[3]));
       }
       @Override
       public void writeToTextFile(BufferedWriter writer, Employee emp) throws IOException {
        PrintWriter out = new PrintWriter(writer);
         
        // Output the Employee's fields on one line, separated by tabs.
        out.print(emp.getId() + "\t");
        out.print(emp.getName() + "\t");
        out.print(emp.getSalary() + "\t");
        out.print(emp.isRetired());
        
        // Output a newline to indicate the end of this Employee's data in the file.
        out.println();
       }
    • View code file.
    • In CompanyPersister, write the readFromTextFile() and writeToTextFile() methods as per the comments in the code, to read/write a Company to a text file.
       @Override
       public Company readFromTextFile(BufferedReader reader) throws IOException {
        String line = reader.readLine();
        if (line == null) {
         return null;
        }
        
        Company company = new Company(line);
        EmployeePersister empPersister = new EmployeePersister();
        Employee emp;
        while ((emp = empPersister.readFromTextFile(reader)) != null) {
         company.getEmployees().put(emp.getId(),emp);
        }
        return company;
       }
       @Override
       public void writeToTextFile(BufferedWriter writer, Company company) throws IOException {
        PrintWriter out = new PrintWriter(writer);
        
        // Output company name, on its own line.
        out.println(company.getCompanyName());
        
        // Output company employees, one per line.
        EmployeePersister empPersister = new EmployeePersister();
        for (Employee emp: company.getAllEmployees()) {
         empPersister.writeToTextFile(writer, emp);
        } 
       }
    • View code file.
    • Back in main(), uncomment the statements to load/save data at application start-up and shut-down. Run the application, and verify that it successfully loads and saves data to a text file.
      Company theCompany = loadCompany("Company.txt");
      saveCompany("Company.txt", theCompany);
    • View code file.

Lab 3: Binary files

Lab 3: Binary files
  1. Overview of Binary File Output
    • Java provides “stream” classes for writing binary files
      • Here are some of the most commonly used classes
      • T13P10

  2. Creating Output Stream Objects
    • To write binary data to a file, you will typically create 3 objects arranged in cascading manner, like so:
    • T13P11

    • Example:
      • ReadingWritingBinFiles.java, demoWritingBinFiles()
  3. Overview of Binary File Input
    • Java also provides “input stream “ classes for reading binary files
      • Here are some of the most commonly used classes
      • T13P12

  4. Creating Input Stream Objects
    • To read text from a file, you will typically create 3 objects arranged in cascading manner, like so:
    • T13P13

    • Example:
      • ReadingWritingBinFiles.java, demoReadingBinFiles()

Lab 4: Serialization

Lab 4: Serialization
  1. Marking a Class as Serializable
    • To mark a class as serializable:
    • Serializable is a “marker” interface
      • No methods
      • Simply acts as a flag, to indicate “it makes sense to serialize instances of this class type”
        public class BankAccount implements Serializable {
         ...
        }
    • If you try to serialize/deserialize a class that doesn’t implement Serializable:
      • The JVM will throw a NotSerializableException
  2. Serializing an Object
    • To serialize an object:
      • Create an output stream object, e.g. a FileOutputStream
      • Wrap it in an ObjectOutputStream
      • Invoke writeObject() to write an object to the stream
      • Close the stream
    • Example:
      public static void serializeBankAccount(String filename, BankAccount acc) {
       try {
        FileOutputStream  fs = new FileOutputStream(filename);
        ObjectOutputStream os = new ObjectOutputStream(fs);
        os.writeObject(acc);
        os.close();
       } catch (Exception e) {
        e.printStackTrace();
       }
      }
    • View code file.
  3. Deserializing an Object
    • To deserialize an object:
      • Create an input stream object, e.g. a FileInputStream
      • Wrap it in an ObjectInputStream
      • Invoke readObject() to read an object from the stream
      • Close the stream
    • Example:
      public static BankAccount deserializeBankAccount(String filename) {
       BankAccount acc = null;
       try {
        FileInputStream  fs = new FileInputStream(filename);
        ObjectInputStream is = new ObjectInputStream(fs);
        acc = (BankAccount) is.readObject();
        is.close();
       } catch (Exception e) {
        e.printStackTrace();
       }
       return acc;
      }
    • View code file.
  4. What is Serialized / Deserialized?
    • The JVM uses reflection to serialize/deserialize all instance variables in an object
      • Even the private ones!
    • The JVM performs “deep” serialization/deserialization
      • Object graphs are serialized, with object relationships retained
      • The objects in the graph must be serializable
    • Note: The JVM does NOT serialize:
      • Instance variables that are marked as transient
      • Any static variables
  5. Serialization and Inheritance
    • If a superclass is serializable
      • I.e. it implements the Serializable interface
    • Then the subclass also is serializable
      • It automatically inherits the implementation of Serializable from the superclass
  6. Customizing Serialization
    • If you want to, you can customize how an object is serialized / deserialized
      • Implement the following private methods in your class
      • The JVM will invoke these methods if they exist
        public class BankAccount implements Serializable {
         ...
         private void writeObject(ObjectOutputStream os) throws IOException {
          os.defaultWriteObject(); // Optionally invoke normal serialization behavior.
          os.writeInt(42);     // Do some custom serialization.
         }
         private void readObject(ObjectInputStream is) throws IOException, ClassNotFoundException {
          is.defaultReadObject(); // Optionally invoke normal deserialization behavior.
          int life = is.readInt(); // Do some custom deserialization.
         }
         ...
        }
Lab
  1. Serialization
    • Enhance the Employee and Company classes, so that they are serializable. Then add code in Main.java, to implement the deserializeCompany() and serializeCompany() methods.
      import java.io.Serializable;
      import java.util.Scanner;
      public class Employee implements Serializable { ...}
      import java.io.Serializable;
      import java.util.ArrayList;
      import java.util.Collection;
      import java.util.TreeMap;
      public class Company implements Serializable { ... }
    • deserializeCompany() and serializeCompany() methods
       public static Company deserializeCompany(String filename) {
        Company company = null;
        try {
         FileInputStream fs = new FileInputStream(filename);
         ObjectInputStream is = new ObjectInputStream(fs);
         company = (Company) is.readObject();
         is.close();
         System.out.println("Deserialized company data for " + company.getCompanyName());
        } catch (Exception ex) {
         System.err.println("deserializeCompany() exception: " + ex.getMessage());
        }
        return company;
       }
       public static void serializeCompany(String filename, Company company) {
        
        try {
         FileOutputStream fs = new FileOutputStream(filename);
         ObjectOutputStream os = new ObjectOutputStream(fs);
         os.writeObject(company);
         os.close();
         System.out.println("Serialized company data for " + company.getCompanyName());
        } catch (Exception ex) {
         System.err.println("serializeCompany() exception: " + ex.getMessage());
        }
       }
    • View code file.
    • In main(), uncomment the statements to deserialize/serialize data at application start-up and shut-down. Run the application, and verify that it successfully deserializes and serializes data to a Java serialization file.
      Company theCompany = deserializeCompany("Company.ser");
      serializeCompany("Company.ser", theCompany);
    • View code file.

 

Well done. You have completed the tutorial in the Java course. The next tutorial is

14. Accessing Databases using JDBC


Back to beginning
Copyright © 2016 TalkIT®






If you liked this post, please comment with your suggestions to help others.
If you would like to see more content like this in the future, please fill-in our quick survey.
Scroll to Top