How do I use Console class to read user input?

In the previous example, How do I read user input from console using Scanner class?, we use the java.util.Scanner class to read user input. In this example we use another new class introduced in the Java 1.6, the java.io.Console class.

The Console class provide methods like readLine() and readPassword(). The readPassword() method can be used to read user’s password. Using this method the user’s input will not be shown in the console. The password will be returned as an array of char.

package org.kodejava.io;

import java.io.Console;

public class ConsoleDemo {

    public static void main(String[] args) {
        // Get a console object, console can be null if not available.
        Console console = System.console();

        if (console == null) {
            System.out.println("Console is not available.");
            System.exit(1);
        }

        // Read username from the console
        String username = console.readLine("Username: ");

        // Read password, the password will not be echoed to the
        // console screen and returned as an array of characters.
        char[] password = console.readPassword("Password: ");

        if (username.equals("admin") && String.valueOf(password).equals("secret")) {
            console.printf("Welcome to Java Application %1$s.%n", username);
        } else {
            console.printf("Invalid username or password.%n");
        }
    }
}

The result of the code snippet above is:

Username: admin
Password:
Welcome to Java Application admin.

How do I store objects in file?

This example demonstrates how to use the java.io.ObjectOutputStream and java.io.ObjectInputStream classes to write and read a serialized object. We will create a Book that implements java.io.Serializable interface. The Book class has a constructor that accept all the book detail information.

To write an object to a stream we call the writeObject() method of the ObjectOutputStream class and pass the serialized object to it. To read the object back we call the readObject() method of the ObjectInputStream class.

package org.kodejava.io;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class ObjectStoreExample {

    public static void main(String[] args) {
        // Create instances of FileOutputStream and ObjectOutputStream.
        try (FileOutputStream fos = new FileOutputStream("books.dat");
             ObjectOutputStream oos = new ObjectOutputStream(fos)) {

            // Create a Book instance. This book object then will be stored in
            // the file.
            Book book = new Book("0-07-222565-3", "Hacking Exposed J2EE & Java",
                    "Art Taylor, Brian Buege, Randy Layman");

            // By using writeObject() method of the ObjectOutputStream we can
            // make the book object persistent on the books.dat file.
            oos.writeObject(book);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // We have the book saved. Now it is time to read it back and display
        // its detail information.
        try (FileInputStream fis = new FileInputStream("books.dat");
             ObjectInputStream ois = new ObjectInputStream(fis)) {

            // To read the Book object use the ObjectInputStream.readObject() method.
            // This method return Object type data, so we need to cast it back the
            // origin class, the Book class.
            Book book = (Book) ois.readObject();
            System.out.println(book.toString());

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

// The book object will be saved using ObjectOutputStream class and to be read
// back using ObjectInputStream class. To enable an object to be written to a
// stream we need to make the class implements the Serializable interface.
class Book implements Serializable {
    private final String isbn;
    private final String title;
    private final String author;

    public Book(String isbn, String title, String author) {
        this.isbn = isbn;
        this.title = title;
        this.author = author;
    }

    @Override
    public String toString() {
        return "Book{" +
                "isbn='" + isbn + '\'' +
                ", title='" + title + '\'' +
                ", author='" + author + '\'' +
                '}';
    }
}

The result of the code snippet above is:

Book{isbn='0-07-222565-3', title='Hacking Exposed J2EE & Java', author='Art Taylor, Brian Buege, Randy Layman'}

How do I use DataInputStream and DataOutputStream?

java.io.DataOutputStream and java.io.DataInputStream give us the power to write and read primitive data type to a media such as file. Both of these classes have the corresponding methods to write primitive data type and to read it back.

Using this class make it easier to read int, float, double data and others without needing to interpret if the data should be an int or a float data. Let’s see our code below.

package org.kodejava.io;

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class PrimitiveStreamExample {

    public static void main(String[] args) {
        // Prepares some data to be written to a file.
        int cityIdA = 1;
        String cityNameA = "Green Lake City";
        int cityPopulationA = 500000;
        float cityTempA = 15.50f;

        int cityIdB = 2;
        String cityNameB = "Salt Lake City";
        int cityPopulationB = 250000;
        float cityTempB = 10.45f;

        /*
        Create an instance of FileOutputStream with cities.dat as the file
        name to be created. Then we pass the input stream object in the
        DataOutputStream constructor.
        */
        try (FileOutputStream fos = new FileOutputStream("cities.dat");
             DataOutputStream dos = new DataOutputStream(fos)) {

            /*
             Below we write some data to the cities.dat. DataOutputStream
             class have various method that allow us to write primitive type
             data and string. There are method called writeInt(),
             writeFloat(), writeUTF(), etc.
            */
            dos.writeInt(cityIdA);
            dos.writeUTF(cityNameA);
            dos.writeInt(cityPopulationA);
            dos.writeFloat(cityTempA);

            dos.writeInt(cityIdB);
            dos.writeUTF(cityNameB);
            dos.writeInt(cityPopulationB);
            dos.writeFloat(cityTempB);
        } catch (IOException e) {
            e.printStackTrace();
        }

        /*
         Now we have a cities.dat file with some data in it. Next you'll see
         how easily we can read back this data and display it. Just like the
         DataOutputStream the DataInputStream class have the corresponding
         read methods to read data from the file. Some method names
         are readInt(), readFloat(), readUTF(), etc.
        */
        try (FileInputStream fis = new FileInputStream("cities.dat");
             DataInputStream dis = new DataInputStream(fis)) {

            // Read the first data
            int cityId1 = dis.readInt();
            String cityName1 = dis.readUTF();
            int cityPopulation1 = dis.readInt();
            float cityTemperature1 = dis.readFloat();

            printOut(cityId1, cityName1, cityPopulation1, cityTemperature1);

            // Read the second data
            int cityId2 = dis.readInt();
            String cityName2 = dis.readUTF();
            int cityPopulation2 = dis.readInt();
            float cityTemperature2 = dis.readFloat();

            printOut(cityId2, cityName2, cityPopulation2, cityTemperature2);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void printOut(int cityId1, String cityName1, int cityPopulation1, float cityTemperature1) {
        System.out.println("Id: " + cityId1);
        System.out.println("Name: " + cityName1);
        System.out.println("Population: " + cityPopulation1);
        System.out.println("Temperature: " + cityTemperature1);
    }
}

The generated result of our program are:

Id: 1
Name: Green Lake City
Population: 500000
Temperature: 15.5
Id: 2
Name: Salt Lake City
Population: 250000
Temperature: 10.45

How do I use RandomAccessFile class?

This is an example of using RandomAccessFile class to read and write data to a file. Using RandomAccessFile enable us to read or write to a specific location in the file at the file pointer. Imagine the file as a large array of data that have their own index.

In the code below you’ll see how to create an instance of RandomAccessFile and define its operation mode (read or write). After we create an object we write some data, some book’s titles to the file. The last few line of the codes demonstrate how to read file data.

package org.kodejava.io;

import java.io.IOException;
import java.io.RandomAccessFile;

public class RandomAccessFileExample {

    public static void main(String[] args) {
        try {
            // Let's write some book's title to the end of the file
            String[] books = new String[5];
            books[0] = "Professional JSP";
            books[1] = "The Java Application Programming Interface";
            books[2] = "Java Security";
            books[3] = "Java Security Handbook";
            books[4] = "Hacking Exposed J2EE & Java";

            // Create a new instance of RandomAccessFile class. We'll do a "r"
            // read and "w" write operation to the file. If you want to do a write
            // operation you must also allow read operation to the RandomAccessFile
            // instance.
            RandomAccessFile raf = new RandomAccessFile("books.dat", "rw");
            for (String book : books) {
                raf.writeUTF(book);
            }

            // Write another data at the end of the file.
            raf.seek(raf.length());
            raf.writeUTF("Servlet & JSP Programming");

            // Move the file pointer to the beginning of the file
            raf.seek(0);

            // While the file pointer is less than the file length, read the
            // next strings of data file from the current position of the
            // file pointer.
            while (raf.getFilePointer() < raf.length()) {
                System.out.println(raf.readUTF());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

The result of our program are:

Professional JSP
The Java Application Programming Interface
Java Security
Java Security Handbook
Hacking Exposed J2EE & Java
Servlet & JSP Programming

How do I create a directories recursively?

The code below use File.mkdirs() method to create a collection of directories recursively. It will create a directory with all its necessary parent directories.

package org.kodejava.io;

import java.io.File;

public class CreateDirs {
    public static void main(String[] args) {
        // Define a deep directory structures and create all the
        // directories at once.
        String directories = "D:/kodejava/a/b/c/d/e/f/g/h/i";
        File file = new File(directories);

        // The mkdirs will create folder including any necessary
        // but nonexistence parent directories. This method returns
        // true if and only if the directory was created along with
        // all necessary parent directories.
        boolean created = file.mkdirs();
        System.out.println("Directories created? " + created);
    }
}