How do I read all lines from a file?

The java.nio.file.Files.readAllLines() method read all lines from a file. This method ensures that the file is closed when all bytes have been read or an I/O error, or other runtime exception, is thrown. Bytes from the file are decoded into characters using the specified charset.

Note that this method is intended for simple cases where it is convenient to read all lines in a single operation. It is not intended for reading in large files. This method is available since Java 7.

package org.kodejava.io;

import java.net.URI;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Objects;

public class ReadFileAsListDemo {
    public static void main(String[] args) {
        ReadFileAsListDemo demo = new ReadFileAsListDemo();
        demo.readFileAsList();
    }

    private void readFileAsList() {
        String fileName = "/data.txt";

        try {
            URI uri = Objects.requireNonNull(this.getClass().getResource(fileName)).toURI();
            List<String> lines = Files.readAllLines(Paths.get(uri),
                    Charset.defaultCharset());

            for (String line : lines) {
                System.out.println(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

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.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("F:/Temp/Data/data.tar.gz");
        ext = FileExtension.getFileExtension(file);
        System.out.println("Ext = " + ext);

        file = new File("F:/Temp/Data/HelloWorld.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 to simplify the process.

package org.kodejava.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 = "F:/Temp/source";
        File srcDir = new File(source);

        String destination = "F:/Temp/target";
        File destDir = new File(destination);

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

Maven Dependencies

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.14.0</version>
</dependency>

Maven Central

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 accepts two parameters, the source directory and the destination directory. The source directory should be available while if the destination directory doesn’t exist, it will be created.

package org.kodejava.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 = "F:/Temp/source";
        File srcDir = new File(source);

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

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

Maven Dependencies

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.14.0</version>
</dependency>

Maven Central

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.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("README.md");
        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 call 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();
        }
    }
}