Movatterモバイル変換


[0]ホーム

URL:


Documentation

The Java™ Tutorials
Basic I/O
I/O Streams
Byte Streams
Character Streams
Buffered Streams
Scanning and Formatting
Scanning
Formatting
I/O from the Command Line
Data Streams
Object Streams
File I/O (Featuring NIO.2)
What Is a Path? (And Other File System Facts)
The Path Class
Path Operations
File Operations
Checking a File or Directory
Deleting a File or Directory
Copying a File or Directory
Moving a File or Directory
Managing Metadata (File and File Store Attributes)
Reading, Writing, and Creating Files
Random Access Files
Creating and Reading Directories
Links, Symbolic or Otherwise
Walking the File Tree
Finding Files
Watching a Directory for Changes
Other Useful Methods
Legacy File I/O Code
Summary
Questions and Exercises
Trail: Essential Java Classes
Lesson: Basic I/O
Section: File I/O (Featuring NIO.2)
Home Page >Essential Java Classes >Basic I/O
« Previous • Trail • Next »

The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.
SeeDev.java for updated tutorials taking advantage of the latest releases.
SeeJava Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.
SeeJDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.

File Operations

TheFiles class is the other primary entrypoint of thejava.nio.file package. This class offers a rich set of static methods for reading, writing, and manipulating files and directories. TheFiles methods work on instances ofPath objects. Before proceeding to the remaining sections, you should familiarize yourself with the following common concepts:

Releasing System Resources

Many of the resources that are used in this API, such as streams or channels, implement or extend thejava.io.Closeable interface. A requirement of aCloseable resource is that theclose method must be invoked to release the resource when no longer required. Neglecting to close a resource can have a negative implication on an application's performance. Thetry-with-resources statement, described in the next section, handles this step for you.

Catching Exceptions

With file I/O, unexpected conditions are a fact of life: a file exists (or doesn't exist) when expected, the program doesn't have access to the file system, the default file system implementation does not support a particular function, and so on. Numerous errors can be encountered.

All methods that access the file system can throw anIOException. It is best practice to catch these exceptions by embedding these methods into atry-with-resources statement, introduced in the Java SE 7 release. Thetry-with-resources statement has the advantage that the compiler automatically generates the code to close the resource(s) when no longer required. The following code shows how this might look:

Charset charset = Charset.forName("US-ASCII");String s = ...;try (BufferedWriter writer = Files.newBufferedWriter(file, charset)) {    writer.write(s, 0, s.length());} catch (IOException x) {    System.err.format("IOException: %s%n", x);}

For more information, seeThe try-with-resources Statement.

Alternatively, you can embed the file I/O methods in atry block and then catch any exceptions in acatch block. If your code has opened any streams or channels, you should close them in afinally block. The previous example would look something like the following using the try-catch-finally approach:

Charset charset = Charset.forName("US-ASCII");String s = ...;BufferedWriter writer = null;try {    writer = Files.newBufferedWriter(file, charset);    writer.write(s, 0, s.length());} catch (IOException x) {    System.err.format("IOException: %s%n", x);} finally {    if (writer != null) writer.close();}

For more information, seeCatching and Handling Exceptions.

In addition toIOException, many specific exceptions extendFileSystemException. This class has some useful methods that return the file involved(getFile), the detailed message string(getMessage), the reason why the file system operation failed(getReason), and the "other" file involved, if any(getOtherFile).

The following code snippet shows how thegetFile method might be used:

try (...) {    ...    } catch (NoSuchFileException x) {    System.err.format("%s does not exist\n", x.getFile());}

For purposes of clarity, the file I/O examples in this lesson may not show exception handling, but your code should always include it.

Varargs

SeveralFiles methods accept an arbitrary number of arguments when flags are specified. For example, in the following method signature, the ellipses notation after theCopyOption argument indicates that the method accepts a variable number of arguments, orvarargs, as they are typically called:

Path Files.move(Path, Path,CopyOption...)

When a method accepts a varargs argument, you can pass it a comma-separated list of values or an array (CopyOption[]) of values.

In themove example, the method can be invoked as follows:

import static java.nio.file.StandardCopyOption.*;Path source = ...;Path target = ...;Files.move(source,           target,           REPLACE_EXISTING,           ATOMIC_MOVE);

For more information about varargs syntax, seeArbitrary Number of Arguments.

Atomic Operations

SeveralFiles methods, such asmove, can perform certain operations atomically in some file systems.

Anatomic file operation is an operation that cannot be interrupted or "partially" performed. Either the entire operation is performed or the operation fails. This is important when you have multiple processes operating on the same area of the file system, and you need to guarantee that each process accesses a complete file.

Method Chaining

Many of the file I/O methods support the concept ofmethod chaining.

You first invoke a method that returns an object. You then immediately invoke a method onthat object, which returns yet another object, and so on. Many of the I/O examples use the following technique:

String value = Charset.defaultCharset().decode(buf).toString();UserPrincipal group =    file.getFileSystem().getUserPrincipalLookupService().         lookupPrincipalByName("me");

This technique produces compact code and enables you to avoid declaring temporary variables that you don't need.

WhatIs a Glob?

Two methods in theFiles class accept a glob argument, but what is aglob?

You can use glob syntax to specify pattern-matching behavior.

A glob pattern is specified as a string and is matched against other strings, such as directory or file names. Glob syntax follows several simple rules:

Here are some examples of glob syntax:


Note: If you are typing the glob pattern at the keyboard and it contains one of the special characters, you must put the pattern in quotes ("*"), use the backslash (\*), or use whatever escape mechanism is supported at the command line.

The glob syntax is powerful and easy to use. However, if it is not sufficient for your needs, you can also use a regular expression. For more information, see theRegular Expressions lesson.

For more information about the glob syntax, see the API specification for thegetPathMatcher method in theFileSystem class.

Link Awareness

TheFiles class is "link aware." EveryFiles method either detects what to do when a symbolic link is encountered, or it provides an option enabling you to configure the behavior when a symbolic link is encountered.

« PreviousTrailNext »

About Oracle |Contact Us |Legal Notices |Terms of Use |Your Privacy Rights

Copyright © 1995, 2024 Oracle and/or its affiliates. All rights reserved.

Previous page: Path Operations
Next page: Checking a File or Directory

[8]ページ先頭

©2009-2025 Movatter.jp