Tutorial

Java Files - java.nio.file.Files Class

Published on August 3, 2022
Default avatar

By Pankaj

Java Files - java.nio.file.Files Class

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Java Files class was introduced in Java 1.7 and is a part of java.nio.file package.

Java Files Class

java Files class, java NIO Files

  • Java Files class contains static methods that work on files and directories.
  • This class is used for basic file operations like create, read, write, copy and delete the files or directories of the file system.

Before move ahead let’s have a look at the below terms first:

  1. Path: This is the interface that replaces java.io.File class as the representation of a file or a directory when we work in Java NIO.
  2. Paths: This class contains a static method to create Path instance.

java.nio.file.Path interface is just like the old java.io.File class. Path represents location of the file and when we create a Path to new file, it does not create actual file until we create it using Files.createFile(Path filePath). java file path, Java NIO Files Paths As we can see in above diagram, Paths class is used to create instance of Path and Files class uses Path instance to work on a file. File and Path objects know how to convert to the other, that’s how we can use older code to interact with new Files utility.

Java IO vs NIO

Java IO vs NIO

How to Create Path

We can create an object of Path by calling Paths.get(String first, String... more) method of Paths class.

Path path1 = Paths.get("/tmp/file.txt"); // For UNIX

Path path2 = Paths.get("D:/data/file.txt"); // For Windows

We can also create an object of Path by separating parts of the path in Paths.get() method.

Path path1 = Paths.get("/tmp", "file.txt");

Path path2 = Paths.get("D:", "data", "file.txt");

Path path3 = Paths.get("D:/data", "file.txt") ;

As we can see, we can pass folder and file name in Paths.get() method separately.

Java Files Methods

Java NIO Files class contains static methods that is used for manipulating files and directories and those methods mostly works on Path object. Let’s have a look at below methods of Files class:

  1. copy(InputStream in, Path target, CopyOption… options): This method copies all bytes from specified input stream to specified target file and it returns number of bytes read or written as long value.
  2. copy(Path source, OutputStream out): This method copies all bytes from specified source file to given output stream and it returns number of bytes read or written as long value.
  3. copy(Path source, Path target, CopyOption… options): This method copies given source file to specified target file and it returns path of target file.
  4. createDirectories(Path dir, FileAttribute<?>… attrs): This method creates a directories using given path by creating all nonexistent parent directories first. This method will not throw an exception if the directory could not be created because it already exists. FileAttribute is an optional parameter to set automatically when creating the nonexistent directories and it returns the path of created directory.
  5. createDirectory(Path dir, FileAttribute<?>… attrs): This method creates a directory using given path, if it creates directory successfully it will returns the path of the created directory. If directory is already exists then it will throw nio.file.FileAlreadyExistsException.
  6. createFile(Path path, FileAttribute<?>… attrs): This method creates a new empty file using given path and returns path of newly created file if it creates it successfully. If file is already exists then it will throw nio.file.FileAlreadyExistsException.
  7. createTempDirectory(Path dir, String prefix, FileAttribute<?>… attrs): This method creates a Temporary directory using given path and it will generate the name of directory using given prefix. It will return the path of newly created temporary directory.
  8. createTempDirectory(String prefix, FileAttribute<?>… attrs): This method creates a Temporary directory in the default temporary-file directory and generate the name of directory using given prefix. It will return the path of newly created temporary directory which is associated with the default File System.
  9. createTempFile(Path dir, String prefix, String suffix, FileAttribute<?>… attrs): This method creates a temporary file at specified directory and generates the file name using given prefix and suffix and returns the path of newly created file.
  10. createTempFile(String prefix, String suffix, FileAttribute<?>… attrs): This method creates a temporary file at default temporary-file directory and generates the file name using given prefix and suffix and returns the path of newly created file.
  11. delete(Path path): This is a void method and simply deletes the file from specified path. This method throws NoSuchFileException if the file is not exists at specified path and if the file is directory and it may not empty and cannot be deleted, in this case it will throws
  12. deleteIfExists(Path path): This methods checks if file exists before delete the file and returns boolean value true if the file at the given path gets deleted successfully and returns false if the file is not exists at given path. If the file is directory and it may not empty and cannot be deleted, in this case it will throws
  13. exists(Path path): This method checks if file exists at specified path and if the file exists it will return true or else it returns false.
  14. getLastModifiedTime(Path path, Linkoption… options): This method returns a file’s last modified time from given path as
  15. getOwner(Path path, Linkoption… options): This method returns UserPrincipal representing the owner of the file at given path.
  16. isDirectory(Path path, Linkoption… options): This method checks if the file is a directory from given path. It returns true if the file is directory and false if the file does not exists or is not a directory or it cannot be determined if the file is a directory or not.
  17. isExecutable(Path path): This method checks whether file at given path is executable or not and it also checks that file exists and that this JVM has appropriate privilege to execute the file. It returns true if the file is exists at given path and is executable and false if the file does not exists or JVM has not sufficient privilege to execute file or access cannot be determined.
  18. isHidden(Path path): This method tells whether file at given is considered as hidden or not. The exact definition of hidden is platform or provider dependent. In case of UNIX system a file is considered hidden if the name of file is starts with period character (‘.’) And in case of WINDOWS file is considered as hidden if it is not a directory and DOS hidden attribute is set. It returns true if the file at given path is considered as hidden or else false.
  19. isReadable(Path path): This method tests whether the file at given path is readable or not. It reruns true if the file at specified path exists and is readable and false if the file does not exists or read access is denied because JVM does not has sufficient privilege or access cannot be determined.
  20. isWritable(Path path): This method tests whether the file at given path is writable or not. It reruns true if the file at specified path exists and is writable and false if the file does not exists or write access is denied because JVM does not has sufficient privilege or access cannot be determined.
  21. move(Path source, Path target, CopyOption… options): This method move or rename a source file to target file and returns the path of target file. Option parameter may include following : REPLACE_EXISTING: It means if the target file exists then replaces it if it is not a non-empty directory. ATOMIC_MOVE: It means move is performed as atomic file system operation and all other options are ignored. This method throws FileAleadyExistsException if the target file exists but cannot be replaced because the REPLACE_EXISTING option is not specified. This method throws DirectoryNotEmptyException if REPlACE_EXISTING option is specified but the file cannot be replaced because it is a non-empty directory.
  22. newBufferedReader(Path path, Charset cs): This method opens a file using given path for reading by returning a BufferedReader that used to read text from the file.Bytes from the file are decoded into characters using the specified charset.
  23. newBufferedWriter(Path path, Charset cs, Openoption… options): This method opens or creates a file using given path for writing by returning BufferedWriter that used to write text to the file. The options parameter specifies how the file is created or opened. If no option is specified then it consider CREATE, TRUNCATE_EXISTING and WRITE options by default, this means it opens the file for writing and creates if the file does not exist or truncate existing file to size of 0 if it exists. This method throws UnsupportedOperationException if unsupported option is specified.
  24. newByteChannel(Path path, OpenOption… options): This method creates or opens the file using specified path by returning a seekable byte channel to access the file. This method throws UnsupportedOperationException if unsupported option is specified.
  25. newDirectoryStream(Path path): This method opens a directory by returning a DirectoryStream to iterate over all entries in the directory from the specified path. The elements return by DirectoryStream’s iterator are of type Path and each one represents an entry in the directory. This method throws NotDirectoryException if the file at given path could not be opened because it is not a directory.
  26. newDirectoryStream(Path path, Filter<? super Path > filter): This method opens a directory by returning a DirectoryStream to iterate over all entries in the directory from the specified path. The elements return by DirectoryStream’s iterator are of type Path and each one represents an entry in the directory and these entries are filtered by the specified filter. This method throws NotDirectoryException if the file at given path could not be opened because it is not a directory.
  27. newDirectoryStream(Path path, String glob): This method opens a directory by returning a DirectoryStream to iterate over all entries in the directory from the specified path. The elements return by DirectoryStream’s iterator are of type Path and each one represents an entry in the directory and these entries is filtered by matching the String representation of their file names against the specified globbing pattern. This method throws NotDirectoryException if the file at given path could not be opened because it is not a directory and PatternSyntaxException if the pattern is invalid.
  28. newInputStream(Path path, Openoption… options): This method opens a file by returning input stream to read the file from specified path. The options parameter is determines how the file is opened and if no options are specified then it opens the file with READ This method throws IllegalArgumentException if an invalid combination of options is specified and UnsupportedOperationException if an unsupported option is specified.
  29. newOutputStream(Path path, Openoption… options): This method opens a file by returning output stream to write bytes to the file at specified path. The options parameter is determines how the file is opened and If no option is specified then it consider CREATE, TRUNCATE_EXISTING and WRITE options by default, this means it opens the file for writing and creates if the file does not exist or truncate existing file to size of 0 if it exists. This method throws IllegalArgumentException if an invalid combination of options is specified and UnsupportedOperationException if an unsupported option is specified.
  30. notExists(Path path, LinkOption options): This method tests whether the file at specified path does not exists. The options parameter is used to indicate how symbolic links are handled if the file is symbolic link. By default, symbolic links are followed. If the option NOFOLLOW_LINK is present then symbolic links are not followed. This method returns true if file does not exist at specified path and false if the file exists or if its existence cannot be determined.
  31. readAllBytes(Path path): This method reads all the bytes from the file at given path and returns the byte array containing the bytes read from the file.
  32. readAllLines(Path path, Charset cs): This method read all lines from the file at given path and returns the List containing the lines from the file.
  33. size(Path path): This method returns the size of the file at specified path in bytes.
  34. walkFileTree(Path start, FileVisitor<? Super Path> visitor): This method used to traverse the directory. It traverses the directory at specified path recursively and returns the starting file.
  35. write(Path path, byte[] bytes, OpenOption… options): This method writes bytes to a file at specified path. The options parameter specifies how the file is created or opened. If no option is specified then it consider CREATE, TRUNCATE_EXISTING and WRITE options by default, this means it opens the file for writing and creates if the file does not exist or truncate existing file to size of 0 if it exists. All the bytes in byte array are written to the file. This method ensures that the file is closed when all the bytes have been written and returns the path of written file.

Create file Using Files Class

Files class provides createFile(Path filePath, FileAttribute<?>… attrs) method to create file using specified Path. Let’s have a look at the below example program.

package com.journaldev.examples;

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

/**
 * Java Create file using Files class
 * 
 * @author pankaj
 *
 */
public class FilesCreateFileExample {

	public static void main(String[] args) {
		
		//initialize Path object
		Path path = Paths.get("D:/data/file.txt");
		//create file
		try {
			Path createdFilePath = Files.createFile(path);
			System.out.println("File Created at Path : "+createdFilePath);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

Output of the above program is below:

File Created at Path : D:\data\file.txt

Create Directories Using Files Class

Files class provides createDirectory(Path dir, FileAttribute<?>… attrs) and createDirectories(Path dir, FileAttribute<?>… attrs) methods to create single and multi level directories using specified Path. Let’s have a look at the below example program.

package com.journaldev.examples;

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

/**
 * Java Create directories using Files class
 * 
 * @author pankaj
 *
 */
public class FilesCreateDirectoriesExample {

	public static void main(String[] args) {
		// initialize Path objects
		Path path1 = Paths.get("D:/pankaj");
		Path path2 = Paths.get("D:/pankaj/java7");
		Path path3 = Paths.get("D:/pankaj/java7/Files");
		
		try {
			Path createdDir1 = Files.createDirectory(path1);//first level directory
			Path createdDir2 = Files.createDirectory(path2);//second level directory
			Path createdDir3 = Files.createDirectory(path3);//all level directories
			System.out.println("First Level Directory Created at Path : "+createdDir1);
			System.out.println("Second Level Directory Created at Path : "+createdDir2);
			System.out.println("All Level Directories Created at Path : "+createdDir3);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Output of the above program is below:

First Level Directory Created at Path : D:\pankaj
Second Level Directory Created at Path : D:\pankaj\java7
All Level Directories Created at Path : D:\pankaj\java7\Files

Convert File to Path and Vice Versa

File and Path objects can be converted to each other using below methods:

File file = new File(“D:/data/file.txt”);

Path path = file.toPath();

File file1 = path.toFile();

Read File Data using Files Class

Files class provides following methods for reading file.

  1. readAllBytes(Path path): This method reads all the bytes from the file at given path and returns the byte array containing the bytes read from the file.
  2. readAllLines(Path path,Charsetcs): This method read all lines from the file at given path and returns the List containing the lines from the file.

Let’s have a look at the below example program.

package com.journaldev.examples;

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

/**
 * Java Files read file example
 * 
 * @author pankaj
 *
 */
public class FilesReadFileExample {

	public static void main(String[] args) {
		
		Path path = Paths.get("D:/data/file.txt");
		try {
			byte[] bs = Files.readAllBytes(path);
			List<String> strings = Files.readAllLines(path);
			
			System.out.println("Read bytes: \n"+new String(bs));
			System.out.println("Read lines: \n"+strings);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

Output of above program is below:

Read bytes: 
Hello world
This is Read file example
Thank you
Read lines: 
[Hello world, This is Read file example, Thank you]

Copy File using Files Class

Files class provide copy(Path source, Path target, CopyOption… options) methodthat copies given source file to specified target file and it returns path of target file. Let’s have a look at the below example program:

package com.journaldev.examples;

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

/**
 * Java Files copy file example
 * 
 * @author pankaj
 *
 */
public class FilesCopyFileExample {

	public static void main(String[] args) {
		Path sourcePath = Paths.get("D:/data/sourceFile.txt");
		Path targetPath = Paths.get("D:/data/targetFile.txt");
		
		try {
			Path path = Files.copy(sourcePath, targetPath,StandardCopyOption.REPLACE_EXISTING);//copy with REPLACE_EXISTING option
			System.out.println("Target file Path : "+path);
			System.out.println("Copied Content : \n"+new String(Files.readAllBytes(path)));
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}

Output of above program is below:

Target file Path : D:\data\targetFile.txt
Copied Content : 
Hello world
This is Copy file example
Thank you

Move File using Files Class

Java Files class provides move(Path source, Path target, CopyOption… options) method that move or rename a source file to target file and returns the path of target file. Option parameter may include following: REPLACE_EXISTING: It means if the target file exists then replaces it if it is not a non-empty directory. ATOMIC_MOVE: It means move is performed as atomic file system operation and all other options are ignored. This method throws FileAleadyExistsException if the target file exists but cannot be replaced because the REPLACE_EXISTING option is not specified. This method throws DirectoryNotEmptyException if REPlACE_EXISTING option is specified but the file cannot be replaced because it is a non-empty directory. Let’s have a look at the below example program:

package com.journaldev.examples;

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

/**
 * Java Files move file example
 * 
 * @author pankaj
 *
 */
public class FilesMoveFileExample {

	public static void main(String[] args) {
		Path sourcePath = Paths.get("D:/data/sourceFile.txt");
		Path targetPath = Paths.get("D:/data/targetFile.txt");
		try {
			Path path = Files.move(sourcePath, targetPath,StandardCopyOption.REPLACE_EXISTING);//move with REPLACE_EXISTING option
			System.out.println("Target file Path : "+path);
			System.out.println("Moved Content : \n"+new String(Files.readAllBytes(path)));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

Write File using Files Class

Java NIO Files class provides write(Path path, byte[] bytes, OpenOption… options) method that writes bytes to a file at specified path. The options parameter specifies how the file is created or opened. If no option is specified then it consider CREATE, TRUNCATE_EXISTING and WRITE options by default. This means it opens the file for writing and creates if the file does not exist or truncate existing file to size of 0 if it exists. All the bytes in byte array are written to the file. This method ensures that the file is closed when all the bytes have been written and returns the path of written file.

package com.journaldev.examples;

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

/**
 * Java Files write file example
 * 
 * @author pankaj
 *
 */
public class FilesWriteFileExample {

	public static void main(String[] args) {
		Path path = Paths.get("D:/data/test.txt");
		try {
			String str = "This is write file Example";
			byte[] bs = str.getBytes();
			Path writtenFilePath = Files.write(path, bs);
			System.out.println("Written content in file:\n"+ new String(Files.readAllBytes(writtenFilePath)));
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}

Walk File Tree

Files class provides walkFileTree(Path start, FileVisitor<? Super Path> visitor) method that is used to traverse the directory. It traverses the directory at specified path recursively and returns the starting file.

package com.journaldev.examples;

import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;

/**
 * Java Files walk file tree example
 * 
 * @author pankaj
 *
 */
public class FilesWalkFileTreeExample {

	public static void main(String[] args) {
		Path path = Paths.get("D:/pankaj");
		try {
			Files.walkFileTree(path, new FileVisitor<Path>() {

				@Override
				public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
					System.out.println("Post Visit Directory: "+dir);
					return FileVisitResult.CONTINUE;
				}

				@Override
				public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
					System.out.println("Pre Visit Directory: "+dir);
					return FileVisitResult.CONTINUE;
				}

				@Override
				public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
					System.out.println("Visit File: "+file);
					return FileVisitResult.CONTINUE;
				}

				@Override
				public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
					System.out.println("Visit Failed File: "+file);
					return FileVisitResult.CONTINUE;
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}

Output of above program is below:

Pre Visit Directory: D:\pankaj
Pre Visit Directory: D:\pankaj\java6
Pre Visit Directory: D:\pankaj\java6\Files
Visit File: D:\pankaj\java6\Files\file.txt.txt
Post Visit Directory: D:\pankaj\java6\Files
Post Visit Directory: D:\pankaj\java6
Pre Visit Directory: D:\pankaj\java7
Pre Visit Directory: D:\pankaj\java7\Files
Visit File: D:\pankaj\java7\Files\file.txt.txt
Post Visit Directory: D:\pankaj\java7\Files
Post Visit Directory: D:\pankaj\java7
Pre Visit Directory: D:\pankaj\java8
Pre Visit Directory: D:\pankaj\java8\Files
Visit File: D:\pankaj\java8\Files\file.txt.txt
Post Visit Directory: D:\pankaj\java8\Files
Post Visit Directory: D:\pankaj\java8
Post Visit Directory: D:\pankaj

Notice that all the files and folders are processed recursively. This is very useful when you want to do some common processing on all the files, such as rename all the files in a directory recursively. That’s all for Java Files class. Reference: API Doc

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Pankaj

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
January 2, 2020

Hello Pankaj, Please mention why NIO is preferred over Standard IO.

- Supriya

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    December 6, 2018

    Hi Pankaj : very nice set of information but as expected from you the way of presentation can be much more better. I know you long before as we both belong to the same organization . I follow you in youtube that was also very nice.

    - Subhashis

      Try DigitalOcean for free

      Click below to sign up and get $200 of credit to try our products over 60 days!

      Sign up

      Join the Tech Talk
      Success! Thank you! Please check your email for further details.

      Please complete your information!

      Get our biweekly newsletter

      Sign up for Infrastructure as a Newsletter.

      Hollie's Hub for Good

      Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

      Become a contributor

      Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

      Welcome to the developer cloud

      DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

      Learn more
      DigitalOcean Cloud Control Panel