How do I get the extension of a file?

Below is an example that can be used to get the extension of a file. The code below assume that the extension is the last part of the file name after the last dot symbol. For instance if you have a file named data.txt the extension will be txt, but if you have a file named data.tar.gz the extension will be gz.

package org.kodejava.example.io;

import java.io.File;

public class FileExtension {
    private static final String EXT_SEPARATOR = ".";

    public static void main(String[] args) {
        File file = new File("data.txt");
        String ext = FileExtension.getFileExtension(file);
        System.out.println("Ext = " + ext);

        file = new File("C:/Data/Employee/data.tar.gz");
        ext = FileExtension.getFileExtension(file);
        System.out.println("Ext = " + ext);

        file = new File("/home/kodejava/kodejava.org/FileDemo.java");
        ext = FileExtension.getFileExtension(file);
        System.out.println("Ext = " + ext);
    }

    /**
     * Get the extension of the specified file.
     * @param file a file.
     * @return the extension of the file.
     */
    private static String getFileExtension(File file) {
        if (file == null) {
            return null;
        }

        String name = file.getName();
        int extIndex = name.lastIndexOf(FileExtension.EXT_SEPARATOR);

        if (extIndex == -1) {
            return "";
        } else {
            return name.substring(extIndex + 1);
        }
    }
}

How do I move directory to another directory with its entire contents?

Below is an example to move one directory with all its child directory and files to another directory. We can use the FileUtils.moveDirectory() method call to simplify the process.

package org.kodejava.example.commons.io;

import org.apache.commons.io.FileUtils;

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

public class DirectoryMove {
    public static void main(String[] args) {
        String source = "C:/Demo/source";
        File srcDir = new File(source);

        String destination = "C:/Demo/target";
        File destDir = new File(destination);

        try {
            // Move the source directory to the destination directory.
            // The destination directory must not exists prior to the
            // move process.
            FileUtils.moveDirectory(srcDir, destDir);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Maven Dependencies

<!-- http://repo1.maven.org/maven2/commons-io/commons-io/2.6/commons-io-2.6.jar -->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>

How do I copy directory with all its contents to another directory?

To copy a directory with the entire child directories and files we can use a handy method provided by the Apache Commons IO FileUtils.copyDirectory(). This method accept two parameters, the source directory and the destination directory. The source directory should be exist while if the destination directory doesn’t exists it will be created.

package org.kodejava.example.commons.io;

import org.apache.commons.io.FileUtils;

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

public class DirectoryCopy {
    public static void main(String[] args) {
        // An existing directory to copy.
        String source = "C:/Demo/source";
        File srcDir = new File(source);

        // The destination directory to copy to. This directory
        // doesn't exists and will be created during the copy
        // directory process.
        String destination = "C:/Demo/target";
        File destDir = new File(destination);

        try {
            // Copy source directory into destination directory
            // including its child directories and files. When
            // the destination directory is not exists it will
            // be created. This copy process also preserve the
            // date information of the file.
            FileUtils.copyDirectory(srcDir, destDir);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Maven Dependencies

<!-- http://repo1.maven.org/maven2/commons-io/commons-io/2.6/commons-io-2.6.jar -->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>

How do I read file line by line using java.util.Scanner class?

Here is a compact way to read file line by line using the java.util.Scanner class.

package org.kodejava.example.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ScannerReadFile {
    public static void main(String[] args) {
        // Create an instance of File for data.txt file.
        File file = new File("data.txt");
        try {
            // Create a new Scanner object which will read the data
            // from the file passed in. To check if there are more 
            // line to read from it we check by calling the 
            // scanner.hasNextLine() method. We then read line one 
            // by one till all lines is read.
            Scanner scanner = new Scanner(file);
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

How do I read user input from console using java.util.Scanner class?

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

package org.kodejava.example.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 / 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.example.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.example.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.example.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.example.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();
        }
    }
}

How do I use LineNumberReader class to read file?

In this example we use LineNumberReader class to read file contents. What we try to do here is to get the line number of the read data. Instead of introducing another variable; an integer for instance; to keep track the line number we can utilize the LineNumberReader class. This class offers the getLineNumber() method to know the current line of the data that is read.

package org.kodejava.example.io;

import java.io.FileReader;
import java.io.LineNumberReader;

public class LineNumberReaderExample {
    public static void main(String[] args) throws Exception {
        // We'll read a file called student.csv that contains our
        // student information data.
        String filename = Thread.currentThread().getContextClassLoader()
            .getResource("student.csv").getFile();

        // To create the FileReader we can pass in our student data
        // file to the reader. Next we pass the reader into our
        // LineNumberReader class.
        try (FileReader fileReader = new FileReader(filename);
             LineNumberReader lineNumberReader = new LineNumberReader(fileReader)) {
            // If we set the line number of the LineNumberReader here
            // we'll got the line number start from the defined line
            // number + 1

            //lineNumberReader.setLineNumber(400);

            String line;
            while ((line = lineNumberReader.readLine()) != null) {
                // We print out the student data and show what line
                // is currently read by our program.
                System.out.printf("Line Number %s: %s%n",
                    lineNumberReader.getLineNumber(), line);
            }
        }
    }
}

The /resources/student.csv file:

Alice, 7
Bob, 8
Carol, 5
Doe, 6
Earl, 6
Malory, 8

And here is the result of our code snippet above:

Line Number 1: Alice, 7
Line Number 2: Bob, 8
Line Number 3: Carol, 5
Line Number 4: Doe, 6
Line Number 5: Earl, 6
Line Number 6: Malory, 8