Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java NIO Files Class

Java NIO Files Class

java.nio.file.Files is a practical utility class in the Java NIO (New I/O) package, located in java.nio.file package.

java.nio.file.Files It provides a series of static methods to operate on files and directories in the file system, greatly simplifying file I/O operations.

Main Features


Common method categories

**Note:** Many methods throw IOException and require exception handling when used.

The following are the commonly used methods of the java.nio.file.Files class:

Method Description
File operations
static Path copy(Path source, Path target, CopyOption... options) Copy a file from the source path to the target path
static Path move(Path source, Path target, CopyOption... options) Move or rename a file
static void delete(Path path) Delete a file
static boolean deleteIfExists(Path path) Delete a file if it exists
File attributes
static boolean exists(Path path, LinkOption... options) Check whether the file exists
static boolean isDirectory(Path path, LinkOption... options) Check whether a path is a directory
static boolean isRegularFile(Path path, LinkOption... options) Check whether a path is a regular file
static boolean isReadable(Path path) Check whether a file is readable
static boolean isWritable(Path path) Check whether a file is writable
static boolean isExecutable(Path path) Check whether a file is executable
static long size(Path path) Return the file size (bytes)
static FileTime getLastModifiedTime(Path path, LinkOption... options) Get the last modified time of a file
File content operations
static byte[] readAllBytes(Path path) Read all bytes of a file
static List readAllLines(Path path) Read all lines of a file
static List readAllLines(Path path, Charset cs) Read all lines of a file using the specified character set
static Stream lines(Path path) Return a stream of lines in the file
static Stream lines(Path path, Charset cs) Return a stream of lines in the file using the specified character set
static Path write(Path path, byte[] bytes, OpenOption... options) Write bytes to a file
static Path write(Path path, Iterable lines, OpenOption... options) Write text lines to a file
Directory operations
static Stream list(Path dir) List entries in a directory
static DirectoryStream newDirectoryStream(Path dir) Open a directory stream
static Path createDirectory(Path dir, FileAttribute... attrs) Create a directory
static Path createDirectories(Path dir, FileAttribute... attrs) Create a directory (including all non-existent parent directories)
Temporary files/directories
static Path createTempFile(Path dir, String prefix, String suffix, FileAttribute... attrs) Create temporary file
static Path createTempDirectory(Path dir, String prefix, FileAttribute... attrs) Create a temporary directory
Others
static Path createFile(Path path, FileAttribute... attrs) Create a new file
static SeekableByteChannel newByteChannel(Path path, OpenOption... options) Open or create a file, returning a seekable byte channel
static InputStream newInputStream(Path path, OpenOption... options) Open a file input stream
static OutputStream newOutputStream(Path path, OpenOption... options) Open a file output stream
static BufferedReader newBufferedReader(Path path) Open a buffered reader
static BufferedWriter newBufferedWriter(Path path, OpenOption... options) Open a buffered writer
static String probeContentType(Path path) Probe the file content type

1. File operations

File read/write

Example

// Read all lines of a file

List

<
String
lines
=

Files.

readAllLines

(

path

)

;

// Write to a file

Files.

write

(

path, content.

getBytes

(

)

)

;

// Append writing

Files.

write

(

path, content.

getBytes

(

)

, StandardOpenOption.

APPEND

)

;

File copy/move/delete

Example

// Copy a file

Files.

copy

(

sourcePath, targetPath

)

;

// Move/rename a file

Files.

move

(

sourcePath, targetPath

)

;

// Delete a file

Files.

delete

(

path

)

;

2. Directory operations

Create a directory

Example

// Create a single-level directory

Files.

createDirectory

(

path

)

;

// Create a multi-level directory

Files.

createDirectories

(

path

)

;

Directory traversal

Example

// Traverse directory

try

(

Stream

<
Path
paths
=

Files.

list

(

directoryPath

)

)

{

    paths.

forEach

(

System

.

out

::

println

)

;

}

// Recursively traverse directory

try

(

Stream

<
Path
paths
=

Files.

walk

(

directoryPath

)

)

{

    paths.

forEach

(

System

.

out

::

println

)

;

}

3. File attribute operations

Get file attributes

Example

// Check whether the file exists

boolean

exists

=

Files.

exists

(

path

)

;

// Get file size

long

size

=

Files.

size

(

path

)

;

// Get file last modified time

FileTime lastModifiedTime

=

Files.

getLastModifiedTime

(

path

)

;

Set file attributes

Example

// Set file last modified time

Files.

setLastModifiedTime

(

path, FileTime.

fromMillis

(

System

.

currentTimeMillis

(

)

)

)

;

// Set file permissions

Set

<
PosixFilePermission
perms
=

PosixFilePermissions.

fromString

(

"rwxr-x---"

)

;

Files.

setPosixFilePermissions

(

path, perms

)

;


Advanced features

1. File search

Example

// Find files with a specific extension

try

(

Stream

<
Path
paths
=

Files.

find

(

        directoryPath,

       

Integer

.

MAX_VALUE

,

       

(

path, attrs

)

->

path.

toString

(

)

.

endsWith

(

".txt"

)

)

)

{

    paths.

forEach

(

System

.

out

::

println

)

;

}

2. Temporary file operations

Example

// Create the temporary file

Path tempFile

=

Files.

createTempFile

(

"prefix"

,

".suffix"

)

;

// Create temporary directory

Path tempDir

=

Files.

createTempDirectory

(

"tempDir"

)

;

3. File attribute views

Example

// Get file owner

UserPrincipal owner

=

Files.

getOwner

(

path

)

;

// Get file storage information

FileStore store

=

Files.

getFileStore

(

path

)

;


Best Practices

1. Exception handling

Example

try

{

    Files.

copy

(

sourcePath, targetPath, StandardCopyOption.

REPLACE_EXISTING

)

;

}

catch

(

IOException

e

)

{

   

System

.

err

.

println

(

"File operation failed: "

e.

getMessage

(

)

)

;

}

2. Resource cleanup

Example

try

(

Stream

<
String
lines
=

Files.

lines

(

path

)

)

{

    lines.

forEach

(

System

.

out

::

println

)

;

}

// Automatically close the stream

3. Performance considerations


Comparison with traditional I/O

Feature Files class (NIO) Traditional I/O (java.io)
Method type Static methods Instance Methods
Path representation Uses the Path interface Uses the File class
Exception handling Uses IOException uniformly Multiple exception types
Feature richness Richer functionality Basic functionality
Symbolic link handling Native support Limited support
File attribute operations More comprehensive Limited

Pass Files class; Java provides a more modern and powerful file operation API, and it is recommended to use it in new projects to replace the traditional java.io.File class.