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 convert decimal to octal?

From the code snippet below you will learn how to convert decimal to an octal string and converting back from a string of octal number to decimal. For the first conversion we can utilize the Integer.toOctalString() method. This method takes an integer number and will return the string that represent the corresponding octal number.

To convert back from octal string to decimal number we can use the Integer.parseInt() method. Which require two parameter, a string that represent an octal number, and the radix which is 8 from octal number.

package org.kodejava.lang;

public class IntegerToOctalExample {
    public static void main(String[] args) {
        int integer = 1024;
        // Converting integer value to octal string representation.
        String octal = Integer.toOctalString(integer);
        System.out.printf("Octal value of %d is '%s'.\n", integer, octal);

        // Now we converting back from octal string to integer
        // by calling Integer.parseInt and passing 8 as the radix.
        int original = Integer.parseInt(octal, 8);
        System.out.printf("Integer value of octal '%s' is %d.%n", octal, original);

        // When for formatting purposes we can actually use printf
        // or String.format to display an integer value in other
        // format (o = octal, h = hexadecimal).
        System.out.printf("Octal value of %1$d is '%1$o'.\n", integer);
    }
}

Here is the result of our program.

Octal value of 1024 is '2000'.
Integer value of octal '2000' is 1024.
Octal value of 1024 is '2000'.

How do I convert decimal to binary?

In this example you will learn how to convert decimal number to binary number. To convert decimal number to binary we can use Integer.toBinaryString() method. This method takes a single parameter of integer and return a string that represent the equal binary number.

If you want to convert the other way around, from binary string to decimal, you can use the Integer.parseInt() method. This method takes two parameters. First, the string that represents a binary number to be parsed. The second parameter is the radix to be used while parsing, in case for binary number the radix is 2.

package org.kodejava.lang;

public class IntegerToBinaryExample {
    public static void main(String[] args) {
        int integer = 127;
        String binary = Integer.toBinaryString(integer);
        System.out.println("Binary value of " + integer + " is "
                + binary + ".");

        int original = Integer.parseInt(binary, 2);
        System.out.println("Integer value of binary '" + binary
                + "' is " + original + ".");
    }

}

Here is the result of our program.

Binary value of 127 is 1111111.
Integer value of binary '1111111' is 127.