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.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();

        if (files != null) {
            // 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();
        if (strings != null) {
            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, and we can write
        // it using lambda expression as follow.
        FilenameFilter filter = (dir, name) -> name.endsWith(".docx");

        // Give me just a .doc files in your directory.
        File[] docs = gamesDir.listFiles(filter);
        if (docs != null) {
            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 2017 is a directory
D:\Games\GameHouse is a directory
D:\Games\Sierra is a directory
D:\Games\testing.doc.docx is a file
D:\Games\TTD is a directory

The String[] array returned:

File = AOE
File = Championship Manager 2017
File = GameHouse
File = Sierra
File = testing.docx
File = TTD

The File[] array using FilenameFilter result:

Doc file = D:\Games\testing.docx

How do I create a new directory in Java?

We create a directory by calling mkdir() method of the File object. This method returns true if and only if the directory was successfully created. If false was returned, no directory is created. This could be caused, for example that the directory was already exists.

package org.kodejava.io;

import java.io.File;

public class CreateDirectoryExample {
    public static void main(String[] args) {
        File file = new File("tmpdir");

        if (file.mkdir()) {
            System.out.println("Directory = " + file.getAbsolutePath());
        } else {
            System.out.println("No directory was created");
        }
    }
}

Here is the result of the program:

Directory = F:\Wayan\Kodejava\kodejava-example\tmpdir

How do I get the absolute path of a file in Java?

The following code snippet shows you how to get the absolute path of a file. To do this we use the java.io.File object getAbsolutePath() method.

package org.kodejava.io;

import java.io.File;

public class AbsolutePathExample {
    public static void main(String[] args) {
        // Create an instance of File called file.
        File file = new File("README.md");

        // Now we want to know where is exactly this file is located in our file 
        // system. To do this we can use the getAbsolutePath() method of the File
        // class.
        String absolutePath = file.getAbsolutePath();

        // Print out the JavaProgrammingBook.pdf location to the console.
        System.out.println("AbsolutePath = " + absolutePath);
    }
}

Here is the result of the program:

AbsolutePath = F:\Wayan\Kodejava\kodejava-example\README.md

How do I get file size in Java?

This example will show you how to get the size of a file. To obtain the size of a file you can use the File‘s length() method. The length() method return the file size in bytes.

package org.kodejava.io;

import java.io.File;

public class FileSize {
    public static void main(String[] args) {
        File file = new File("README.md");

        // Get the size of a file in bytes.
        long fileSize = file.length();

        // Using Java printf() method to print the file size
        System.out.printf("File size: %,d bytes.%n", fileSize);
    }
}

This will print something like:

File size: 51,981 bytes.

If you want to format the file size in Kilobytes, Megabytes or Gigabytes check the following example How do I create a human-readable file size?.

How do I get file’s last modification date?

To get file last modification date we can use the lastModified() method of the File class. This method returns a long value. After getting this value you can create an instance of java.util.Date class and pass this value as the parameter. This Date will hold the file’s last modification date.

package org.kodejava.io;

import java.io.File;
import java.util.Date;

public class FileLastModificationDate {
    public static void main(String[] args) {
        // Create an instance of file object.
        File file = new File("README.md");
        if (file.exists()) {
            // Get the last modification information.
            long lastModified = file.lastModified();

            // Create a new date object and pass last modified
            // information to the date object.
            Date date = new Date(lastModified);

            // We know when the last time the file was modified.
            System.out.println(date);
        }
    }
}