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 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);
    }
}

How can I change file attribute to read only?

This code demonstrate how we can modify file attribute to be read only. File class has a setReadOnly() method to make file read only and a canWrite() method to know whether it is writable or not.

package org.kodejava.io;

import java.io.File;

public class FileReadOnlyExample {
    public static void main(String[] args) throws Exception {
        File file = new File("ReadOnly.txt");

        // Create a file only if it doesn't exist.
        boolean created = file.createNewFile();

        // Set file attribute to read only so that it cannot be written
        boolean succeeded = file.setReadOnly();

        // We are using the canWrite() method to check whether we can
        // modified file content.
        if (file.canWrite()) {
            System.out.println("File is writable!");
        } else {
            System.out.println("File is in read only mode!");
        }
    }
}

This code snippet print the following output:

File is in read only mode!

How do I append data to a text file?

One of the common task related to a text file is to append or add some contents to the file. It’s really simple to do this in Java using a FileWriter class. This class has a constructor that accept a boolean parameter call append. By setting this value to true a new data will be appended at the end of the file when we write a new data to it.

Let’s see an example.

package org.kodejava.io;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class AppendFileExample {
    public static void main(String[] args) {
        File file = new File("user.txt");

        try (FileWriter writer = new FileWriter(file, true)) {
            writer.write("username=kodejava;password=secret" + System.lineSeparator());
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}