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 read user input from console using java.util.Scanner class?

In JDK 1.5 a java.util.Scanner class was introduced to handle user input in console application. This class enable us to read string, integer, long, etc.

package org.kodejava.util;

import java.util.Scanner;

public class ScannerDemo {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Read string input for username
        System.out.print("Username: ");
        String username = scanner.nextLine();

        // Read string input for password
        System.out.print("Password: ");
        String password = scanner.nextLine();

        // Read an integer input for another challenge
        System.out.print("What is 2 + 2: ");
        int result = scanner.nextInt();

        if (username.equals("admin")
                && password.equals("secret") && result == 4) {
            System.out.println("Welcome to Java Application");
        } else {
            System.out.println("Invalid username or password, " +
                    "access denied!");
        }
    }
}

The result of the code snippet:

Username: admin
Password: secret
What is 2 + 2: 4
Welcome to Java Application

How do I use ResourceBundle for i18n?

Creating an application for users in different regions can be hard in terms of the message format for the local region. Java provide a ResourceBundle class that help internationalize our application.

To create resources for i18n (there are 18 letters between the first i and the final n) we need to create a file for each locale our application supported. The file name must be ended in language_COUNTRY.properties. For instance a resource bundle for Locale.UK will be MessagesBundle_en_GB.properties.

When the bundle has been loaded we can use bundle.getString(key) to read specific message from our resource bundle file.

package org.kodejava.util;

import java.util.Locale;
import java.util.ResourceBundle;

public class InternationalizationDemo {

    public static void main(String[] args) {
        // Load resource bundle for Locale.UK locale. The resource 
        // bundle will load the MessagesBundle_en_GB.properties file.
        ResourceBundle bundle =
                ResourceBundle.getBundle("MessagesBundle", Locale.UK);
        System.out.println("Message in " + Locale.UK + ": " +
                bundle.getString("greeting"));

        // Change the default locale to Indonesian and get the default 
        // resource bundle for the current locale.
        Locale.setDefault(new Locale("in", "ID"));
        bundle = ResourceBundle.getBundle("MessagesBundle");
        System.out.println("Message in " + Locale.getDefault() + ": " +
                bundle.getString("greeting"));
    }
}

Below are some example of our resource bundle files, these files should be located in our application classpath to enable the ResourceBundle class to read it.

MessagesBundle_en_GB.properties

greeting=Hello, how are you?

MessagesBundle_in_ID.properties

greeting=Halo, apa kabar?

How do I create a client-server socket communication?

In this example you’ll see how to create a client-server socket communication. The example below consist of two main classes, the ServerSocketExample and the ClientSocketExample. The server application listen to port 7777 at the localhost. When we send a message from the client application the server receive the message and send a reply to the client application.

The communication in this example using the TCP socket, it means that there is a fixed connection line between the client application and the server application.

package org.kodejava.net;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.ClassNotFoundException;
import java.lang.Runnable;
import java.lang.Thread;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerSocketExample {
    private static final int PORT = 7777;
    private ServerSocket server;

    private ServerSocketExample() {
        try {
            server = new ServerSocket(PORT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        ServerSocketExample example = new ServerSocketExample();
        example.handleConnection();
    }

    private void handleConnection() {
        System.out.println("Waiting for client message...");

        // The server do a loop here to accept all connection initiated by the
        // client application.
        while (true) {
            try {
                Socket socket = server.accept();
                new ConnectionHandler(socket);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

class ConnectionHandler implements Runnable {
    private final Socket socket;

    ConnectionHandler(Socket socket) {
        this.socket = socket;

        Thread t = new Thread(this);
        t.start();
    }

    public void run() {
        try {
            // Read a message sent by client application
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
            String message = (String) ois.readObject();
            System.out.println("Message Received: " + message);

            // Send a response information to the client application
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            oos.writeObject("Hi...");

            ois.close();
            oos.close();
            socket.close();

            System.out.println("Waiting for client message...");
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
package org.kodejava.net;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.ClassNotFoundException;
import java.net.InetAddress;
import java.net.Socket;

public class ClientSocketExample {
    public static void main(String[] args) {
        try {
            // Create a connection to the server socket on the server application
            InetAddress host = InetAddress.getLocalHost();
            Socket socket = new Socket(host.getHostName(), 7777);

            // Send a message to the client application
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            oos.writeObject("Hello There...");

            // Read and display the response message sent by server application
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
            String message = (String) ois.readObject();
            System.out.println("Message: " + message);

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

To test the application you need to start the server application. Each time you run the client application it will send a message “Hello There…” and in turns the server reply with a message “Hi…”.

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'}