How to get some information about Path object?

The java.nio.Path provides some methods to obtain information about the Path. For example, you can get information about the file name, the parent and the root path. For these you can call the getFileName(), getParent() and getRoot() method respectively.

You can also get the number of elements that make up this Path using the getNameCount() method. And to get the sub-path you can use the subpath() method and specify the starting and ending indexes. The code snippet below demonstrate to you how to get this information.

package org.kodejava.io;

import java.nio.file.Path;
import java.nio.file.Paths;

public class PathInfoExample {
    public static void main(String[] args) {
        // Create a Path for Windows notepad program.
        Path notepad = Paths.get("C:/Windows/System32/notepad.exe");

        // Get some information about the Path object.
        System.out.printf("File name         : %1$s%n", notepad.getFileName());
        System.out.printf("Name count        : %1$s%n", notepad.getNameCount());
        System.out.printf("Parent path       : %1$s%n", notepad.getParent());
        System.out.printf("Root path         : %1$s%n", notepad.getRoot());
        System.out.printf("Sub path from root: %1$s%n", notepad.subpath(0, 2));
    }
}

This code will print something like:

File name         : notepad.exe
Name count        : 3
Parent path       : C:\Windows\System32
Root path         : C:\
Sub path from root: Windows\System32

How do I create a java.nio.Path?

The following code snippet show you how to create a Path. A Path (java.nio.Path) in an interface that represent a location in a file system, such as C:/Windows/System32 or /usr/bin.

To create a Path we can use the java.nio.Paths.get(String first, String... more) methods. Below you can see how to create a Path by passing only the first string and by passing a first string plus some varargs string.

package org.kodejava.io;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class PathCreate {
    public static void main(String[] args) {
        // Create a Path that represents Windows installation location.
        Path windows = Paths.get("C:/Windows");

        // Check to see if the path represent a directory.
        if (Files.isDirectory(windows)) {
            // do something
        }

        // Create a Path that represent Windows programs installation location.
        Path programFiles = Paths.get("C:/Program Files");
        Files.isDirectory(programFiles);

        // Create a Path that represent the notepad.exe program
        Path notepad = Paths.get("C:/Windows", "System32", "notepad.exe");

        // Check to see if the path represent an executable file.
        if (Files.isExecutable(notepad)) {
            // do something
        }
    }
}

How do I copy a file in JDK 7?

In this example you’ll see how to copy a file using the new API provided in the JDK 7. The first step is to define the source and the target of the file to be copied. For this we can use the Path class. To create an instance of Path we use the Paths.get() method by passing the path information as the arguments.

Next we can configure the file copy operation option. For this we can define it as an array of CopyOtion. We can use copy option such as StandardCopyOption.REPLACE_EXISTING and StandardCopyOption.COPY_ATTRIBUTES.

Finally, to copy the file we use the Files.copy() method. We give three arguments to this method, they are the source file, the target file and the copy options information.

Let’s see the code snippet below:

package org.kodejava.io;

import java.io.IOException;
import java.nio.file.*;

public class NioFileCopyDemo {
    public static void main(String[] args) {
        // Define the source and target of the file to be copied.
        Path source = Paths.get("D:/resources/data.txt");
        Path target = Paths.get("D:/resources/data.bak");

        // Define the options used in the file copy process.
        CopyOption[] options = new CopyOption[]{
                StandardCopyOption.REPLACE_EXISTING,
                StandardCopyOption.COPY_ATTRIBUTES
        };

        try {
            // Copy file from source to target using the defined 
            // configuration.
            Files.copy(source, target, options);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

How do I use the DosFileAttributes class?

This example show you how to use the DosFileAttributes class to get file attribute that support DOS file system. This class extends the BasicFileAttributes class. Using the DosFileAttributes class we can read file attributes using isArchive(), isHidden(), isReadOnly() and isSystem() methods.

Let’s see the code snippet below:

package org.kodejava.io;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.DosFileAttributes;

public class DosFileAttributeExample {
    public static void main(String[] args) throws Exception {
        String path = "D:/resources/data.txt";

        Path file = Paths.get(path);
        DosFileAttributes attr = Files.readAttributes(file, DosFileAttributes.class);

        System.out.println("isArchive()  = " + attr.isArchive());
        System.out.println("isHidden()   = " + attr.isHidden());
        System.out.println("isReadOnly() = " + attr.isReadOnly());
        System.out.println("isSystem()   = " + attr.isSystem());
    }
}

The output of the code snippet:

isArchive()  = true
isHidden()   = false
isReadOnly() = false
isSystem()   = false

How do I set the value of file attributes?

This code snippet show you an example on how to set the value of file attributes. Here we will set the DosFileAttributes. To set the value of file attributes we use the Files.setAttributes() method. To set DosFileAttributes we can use the following attributes: "dos:archive", "dos:hidden", "dos:readonly" and "dos:system".

For details let’s see the code snippet below:

package org.kodejava.io;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.DosFileAttributes;

public class UpdateDosFileAttributesExample {
    public static void main(String[] args) throws Exception {
        String path = "D:/resources/data.txt";
        Path file = Paths.get(path);

        // Get current Dos file attributes and print it.
        DosFileAttributes attr = Files.readAttributes(file, DosFileAttributes.class);
        printAttributes(attr);

        // Set a new file attributes.
        Files.setAttribute(file, "dos:archive", false);
        Files.setAttribute(file, "dos:hidden", false);
        Files.setAttribute(file, "dos:readonly", false);
        Files.setAttribute(file, "dos:system", false);

        // Read the newly set file attributes and print it.
        attr = Files.readAttributes(file, DosFileAttributes.class);
        printAttributes(attr);
    }

    /**
     * Print the DosFileAttributes information.
     *
     * @param attr DosFileAttributes.
     */
    private static void printAttributes(DosFileAttributes attr) {
        System.out.println("isArchive()  = " + attr.isArchive());
        System.out.println("isHidden()   = " + attr.isHidden());
        System.out.println("isReadOnly() = " + attr.isReadOnly());
        System.out.println("isSystem()   = " + attr.isSystem());
        System.out.println("----------------------------------------");
    }
}

The output of the code snippet:

isArchive()  = true
isHidden()   = true
isReadOnly() = true
isSystem()   = true
----------------------------------------
isArchive()  = false
isHidden()   = false
isReadOnly() = false
isSystem()   = false
----------------------------------------