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 in Java 7.

package org.kodejava.example.nio;

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

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 = 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 read file using 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 line 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 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.util;

import java.io.File;

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

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

How can I change a 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.
        file.createNewFile();

        // Set file attribute to read only so that it cannot be written
        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 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.getProperty("line.separator"));
            writer.flush();
            writer.close();
        } 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.File;
import java.io.FileReader;
import java.io.LineNumberReader;
import java.net.URI;

public class LineNumberReaderExample {
    public static void main(String[] args) throws Exception {
        FileReader fr = null;
        LineNumberReader lnr = null;

        try {
            // We'll read a file called student.csv that contains our
            // student information data.
            URI uri = LineNumberReaderExample.class
                    .getResource("/student.csv").toURI();
            File file = new File(uri);

            // To create the FileReader we can pass in our student data
            // file to the reader. Next we pass the reader into our 
            // LineNumberReader class.
            fr = new FileReader(file);
            lnr = new LineNumberReader(fr);

            // If we set the line number of the LineNumberReader here
            // we'll got the line number start from the defined line 
            // number + 1

            //lnr.setLineNumber(400);

            String line;
            while ((line = lnr.readLine()) != null) {
                // We print out the student data and show what line
                // is currently read by our program.
                System.out.println("Line Number " + lnr.getLineNumber() +
                        ": " + line);
            }
        } finally {
            // Don't forget to close the stream when we finish reading
            // the file.
            if (fr != null) {
                fr.close();
            }
            if (lnr != null) {
                lnr.close();
            }
        }
    }
}

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

How do I get total space and free space of my disk?

package org.kodejava.example.io;

import java.io.File;

public class FreeSpaceExample {
    public static void main(String[] args) {
        // We create an instance of a File to represent a partition
        // of our file system. For instance here we used a drive D:
        // as in Windows operating system. 
        File file = new File("D:");

        // Using the getTotalSpace() we can get an information of
        // the actual size of the partition, and we convert it to
        // mega bytes. 
        long totalSpace = file.getTotalSpace() / (1024 * 1024);

        // Next we get the free disk space as the name of the
        // method shown us, and also get the size in mega bytes.
        long freeSpace = file.getFreeSpace() / (1024 * 1024);

        // Just print out the values.
        System.out.println("Total Space = " + totalSpace + " Mega Bytes");
        System.out.println("Free Space = " + freeSpace + " Mega Bytes");
    }
}

Here is the result of the program:

Total Space = 76316 Mega Bytes
Free Space = 58412 Mega Bytes

How do I rename a file or directory?

package org.kodejava.example.io;

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

public class FileRenameExample {
    public static void main(String[] args) throws IOException {
        // Creates a new file called OldHouses.csv
        File oldFile = new File("OldHouses.csv");
        oldFile.createNewFile();

        // Creates the target file.
        File newFile = new File("NewHouses.csv");

        // The renameTo() method renames file or directory to a
        // new name by passing the new destination file.
        oldFile.renameTo(newFile);
    }
}

How do I check if a file is hidden?

package org.kodejava.example.io;

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

public class FileHiddenExample {
    public static void main(String[] args) throws IOException {
        File file = new File("Hidden.txt");
        file.createNewFile();

        // We are using the isHidden() method to check whether a file
        // is hidden.
        if (file.isHidden()) {
            System.out.println("File is hidden!");
        } else {
            System.out.println("File is not hidden!");
        }
    }
}

If you want to set the file attribute to hidden in Windows operating system you can see it in the following example: How do I set the value of file attributes?

How do I get the content of a directory?

In this example you’ll see how to read the list of files inside a directory. To get this functionality we can use the File.listFiles() method. This method return an array of File object which can be either an instance of file or directory.

package org.kodejava.example.io;

import java.io.File;
import java.io.FilenameFilter;

public class DirectoryContentExample {
    public static void main(String[] args) {
        File gamesDir = new File("D:/Games");

        // Get a list of file under the specified directory
        // above and return it as an abstract file object.
        File[] files = gamesDir.listFiles();

        // Iterates the content of gamesDir directory, print it
        // and check it whether it was a directory or a file.
        for (File file : files) {
            System.out.println(file + " is a "
                    + (file.isDirectory() ? "directory" : "file"));
        }

        // Here we also get the list of file in the directory but
        // return it just as an array of String.
        String[] strings = gamesDir.list();
        for (String file : strings) {
            System.out.println("File = " + file);
        }

        // Now we want to list the file in the directory but
        // we just want a file with a .doc extension. To do
        // this we first create a FilenameFilter which will
        // be given to the listFiles() method to filter the
        // listing process. The rule of filtering is
        // implemented in the accept() method of the
        // FilenameFilter interface.
        FilenameFilter filter = new FilenameFilter() {
            public boolean accept(File dir, String name) {
                return name.endsWith(".doc");
            }
        };

        // Give me just a .doc files in your directory.
        File[] docs = gamesDir.listFiles(filter);
        for (File doc : docs) {
            System.out.println("Doc file = " + doc);
        }
    }
}

Here is the result of the program:

The File[] array returned:

D:\Games\AOE\ is a directory
D:\Games\Championship Manager 2007 is a directory
D:\Games\GameHouse is a directory
D:\Games\Sierra is a directory
D:\Games\testing.doc is a file
D:\Games\TTD is a directory

The String[] array returned:

File = AOE
File = Championship Manager 2007
File = GameHouse
File = Sierra
File = testing.doc
File = TTD

The File[] array using FilenameFilter result:

Doc file = D:\Games\testing.doc