Programming - Java Files

   Welcome to another Java Tutorial. After looking into Interfaces and Exceptions we will now take a look into Files in Java. We will talk about Streams and how we use them to get input from a file and to write into a file. We will create 2 types of Files: Text and Binary Files. The first ones are simple Text Files that save as plain text. The second one will use serializable Objects and save in "encrypted" Files that use a specific Bit-order. So, without further do let's start out with Streams. 

Streams:

   Streams represent a simple sequence of elements that we get as Input or write as Output into a Location. So, we can use them to get input from a File and put it into a Array or write a variable's value into a File. The Streams are inside of the java.io library and we need to import this library to use Text or "Object" Files.

   The Scanner Object that we used some Posts before is also using a Stream called System.in that gets the input from our keyboard [Scanner s = new Scanner(System.in) ].

   We will talk about 2 different types of Streams. The first is an FileInputStream or FileOutputStream that is used for Text Files and the second one is used for Objects and is called ObjectInputStream or ObjectOutputStream

Let's talk about Text and Binary Files now.

Text Files:

   To create an Input Stream for Files we use the following Code that uses the Scanner Object that we already know with another parameter:

Scanner scan = new Scanner(new FileInputStream("file.txt"));

   For an OutputStream we will use an Object called PrintWriter using the following Code:

PrintWriter w = new PrintWriter(new FileOutputStream("file.txt"));

Then we do Reading using the Scanner Object the same way as we did Keyboard Input with scan.nextLine() and so on. For Writing we use the PrintWriter Object with w.println(variable) to write the variable into a Line and so on.

   Afterwards we have to close our stream using scan.close() or w.close().


Binary Files:

   To create an Input Stream for Binary Files we use the Object called ObjectInputStream that creates a stream of Objects from another Stream that will be a FileInputStream like this:

ObjectInputStream ois = new ObjectInputStream(new FileInputStream("file.dat"));

  An Output Stream for Binary Files uses an Object called ObjectOutputStream and uses in the same way as we did in the InputStream the FileOutputStream like this:

ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("file.dat"));

   Then we do Reading using the ois. readObject(), ois.readInt() functions and so on. An we do Writing using oos.writeObject(object), oos.writeInt(integer) and so on.

   Afterwards, we again have to close the Stream using ois.close() or oos.close().


Serialization:

   To write an Object into a Binary File we have to serialize it first. Serialization is done implementing the Serializable Interface from the java.io library. It's pretty easy to do. All you have to do is implement this Interface using implements Serializable on every class that will be written into a Binary File like this:

public class class_name implements Serializable{
   //DATA
   //METHODS
}

   This Interface doesn't need any Method Implementation in the class that inherits and does everything by it's own. And so using this Interface we already did was was needed to write inside of a Binary File and now we can use the ObjectOutputStream or ObjectInputStream for Writing and Reading into Serializable or Binary Files.


Code:

   We will extend the Code from the previous post (Exceptions) and write 3 Students inside of an Text and Binary File and read them afterwards again and print them out. 

IdNotGreaterThanZeroException:

// Custom Exception
public class IdNotGreaterThanZeroException extends Exception { // IdNotGreaterThanZeroException.java
 public IdNotGreaterThanZeroException() {
     super("Id is less than or equal to zero!");
 }
}


Student:

import java.io.Serializable;
// Object class that makes sure that id is > 0
// and implements the Serializable Interface
// so that it can be written into a Binary File
public class Student implements Serializable{ // Student.java
 private static final long serialVersionUID = -3527004674520842177L;
 private int id;
 private String name;
 private String surname;
 // Overloaded constructor
 public Student(int id, String name, String surname) {
     // try-catch statement for Exception Handling
     try {
         // We are trying to set the id
         setId(id);
     } catch (IdNotGreaterThanZeroException e) {
         // id was less than 0 and an Exception occurs
         System.out.println(e.getMessage()); // print error message
         return; // optional
     }
     setName(name);
     setSurname(surname);
 }
 // GETTERS-SETTERS
 public int getId() {
     return id;
 }
 // method that throws user-defined Exception
 public void setId(int id) throws IdNotGreaterThanZeroException {
     if (id < 0) {
         throw new IdNotGreaterThanZeroException();
     } else {
         this.id = id;
     }
 }
 public String getName() {
     return name;
 }
 public void setName(String name) {
     this.name = name;
 }
 public String getSurname() {
     return surname;
 }
 public void setSurname(String surname) {
     this.surname = surname;
 }
 public String toString() {
     return id + " " + name + " " + surname;
 }
}


TestStudent:

import java.io.*;
import java.util.Scanner;
public class TestStudent { // TestStudent.java
 public static void main(String[] args) {
     // Array of 3 Students
     Student[] students = new Student[3];
     // Give values to our Students
     students[0] = new Student(5, "James", "Mcdonald");
     students[1] = new Student(8, "Nick", "Brown");
     students[2] = new Student(15, "Tim", "Baines");
     System.out.println("TEXTFILE:");
     // write into TextFile checking Exceptions
     try {
         PrintWriter w = new PrintWriter(new FileOutputStream("file.txt"));
         // write String representation of the Students
         w.println(students[0].toString());
         w.println(students[1].toString());
         w.println(students[2].toString());
         w.close(); // close stream
     } catch (IOException ioe) {
         System.out.println(ioe.getMessage());
     }
     // read from TextFile checking Exceptions
     try {
         Scanner scan = new Scanner(new FileInputStream("file.txt"));
         // print out all the Lines checking End of File
         while (scan.hasNext()) {
             System.out.println(scan.nextLine());
         }
         scan.close(); // close stream
     } catch (IOException ioe) {
         System.out.println(ioe.getMessage());
     }
     System.out.println("\nBINARYFILE:");
     // write into BinaryFile checking Exceptions
     try { // write to file
         ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("file.dat"));
         for (int i = 0; i < students.length; i++) {
             // write serializable Object Student to Binary File
             oos.writeObject(students[i]);
         }
         oos.close(); // close stream
     } catch (IOException ioe) {
         System.out.println(ioe.getMessage());
     }
     // read from BinaryFile checking Exceptions
     try { // read from file
         ObjectInputStream ois = new ObjectInputStream(new FileInputStream("file.dat"));
         // print out all the Lines we wrote
         for (int i = 0; i < students.length; i++) {
             // checking if Object is of type Student
             Student s = null;
             try {
                 s = (Student) (ois.readObject());
             } catch (ClassNotFoundException e) {
                 System.out.println(e.getMessage());
             }
             System.out.println(s);
         }
         ois.close(); // close stream
     } catch (IOException ioe) {
         System.out.println(ioe.getMessage());
     }
 }
}

  Those Files are being saved inside of the root directory of our Project in the IDE and if you take a look you will see that the TextFile way is giving a "readable" file in plain text and that the BinaryFile way is giving something that is somewhat coded and that's exactly why we use them. We could also hash or encode our stuff so that it is even safer and afterwards than dehash or decode it to get the real information out of it.

H2
H3
H4
3 columns
2 columns
1 column
5 Comments