倭マン's BLOG

くだらない日々の日記書いてます。 たまにプログラミング関連の記事書いてます。 書いてます。

これからの「Java I/O」の話をしようwww (2) : Files クラス 〜概要〜

Java nio の API を見ていくシリーズ(目次)。 前回java.nio.file パッケージ内の Path インターフェース、Paths クラスを見ました。 今回はこれらと同様に重要なクラス、Files クラスを見ていきます。

Files クラス

Files クラスは、Path オブジェクトを介してファイル、フォルダなどにいろいろな操作を行う static メソッドが定義されているユーティリティ・クラスです。 Paths クラスと同じく、インスタンス化も継承もできません。 感じは commons-io の IOUtils, FileUtils みたいなものかと思います(あんまり使ったことないけど)。

Files に定義されている static メソッドにはファイルを作成したりコピーしたりするようなものが定義されています。 java.io.File クラスについては、これらの操作はインスタンス・メソッドとして定義されていました。 同様に、java.io.File クラスで表されるファイルなどに対してインスタンス・メソッドで提供されていたような機能が、Path インターフェースについては Files クラスに移されているもが多々あるので、もし java.io.File オブジェクトに対して行っていた操作が Path インターフェースに見当たらなければ Files クラスの static メソッドを探してみるといいと思います。

Files クラスに定義されているメソッドには以下のようなものがあります。 分類は拙者の独断と偏見に依ります:

package java.nio.file;

public final class Files {

    //***** ファイル、ディレクトリの作成 *****
    public static Path createFile(Path path, FileAttribute<?>... attrs) throws IOException
    public static Path createDirectories(Path dir, FileAttribute<?>... attrs) throws IOException
    public static Path createDirectory(Path dir, FileAttribute<?>... attrs) throws IOException

    public static Path createTempDirectory(Path dir, String prefix, FileAttribute<?>... attrs) throws IOException
    public static Path createTempDirectory(String prefix, FileAttribute<?>... attrs) throws IOException

    public static Path createTempFile(Path dir, String prefix, String suffix, FileAttribute<?>... attrs) throws IOException
    public static Path createTempFile(String prefix, String suffix, FileAttribute<?>... attrs) throws IOException

    public static Path createLink(Path link, Path existing) throws IOException
    public static Path createSymbolicLink(Path link, Path target, FileAttribute<?>... attrs) throws IOException

    //***** ファイル、ディレクトリの操作 *****
    public static boolean exists(Path path, LinkOption... options)
    public static boolean notExists(Path path, LinkOption... options)

    public static long copy(InputStream in, Path target, CopyOption... options) throws IOException
    public static long copy(Path source, OutputStream out) throws IOException
    public static Path copy(Path source, Path target, CopyOption... options) throws IOException

    public static Path move(Path source, Path target, CopyOption... options) throws IOException

    public static void delete(Path path) throws IOException
    public static boolean deleteIfExists(Path path) throws IOException

    public static Path readSymbolicLink(Path link) throws IOException

    //***** ファイル内容の読み書き*****
    public static boolean isReadable(Path path)
    public static boolean isWritable(Path path)

    public static byte[] readAllBytes(Path path) throws IOException
    public static Path write(Path path, byte[] bytes, OpenOption... options) throws IOException

    public static InputStream newInputStream(Path path, OpenOption... options) throws IOException
    public static OutputStream newOutputStream(Path path, OpenOption... options) throws IOException

    public static SeekableByteChannel
    newByteChannel(Path path, OpenOption... options) throws IOException

    public static SeekableByteChannel
    newByteChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs) throws IOException

    public static List<String> readAllLines(Path path) throws IOException
    public static List<String> readAllLines(Path path, Charset cs) throws IOException

    public static Path
    write(Path path, Iterable<? extends CharSequence> lines, Charset cs, OpenOption... options) throws IOException

    public static Path
    write(Path path, Iterable<? extends CharSequence> lines, OpenOption... options) throws IOException

    public static BufferedReader newBufferedReader(Path path) throws IOException
    public static BufferedReader newBufferedReader(Path path, Charset cs) throws IOException
    public static BufferedWriter newBufferedWriter(Path path, Charset cs, OpenOption... options) throws IOException
    public static BufferedWriter newBufferedWriter(Path path, OpenOption... options) throws IOException

    public static Stream<String> lines(Path path) throws IOException
    public static Stream<String> lines(Path path, Charset cs) throws IOException

    //***** ファイル、ディレクトリの属性 *****
    public static boolean isRegularFile(Path path, LinkOption... options)
    public static boolean isDirectory(Path path, LinkOption... options)
    public static boolean isSymbolicLink(Path path)
    public static boolean isExecutable(Path path)
    public static boolean isHidden(Path path) throws IOException
    public static boolean isSameFile(Path path, Path path2) throws IOException

    public static long size(Path path)

    public static FileTime getLastModifiedTime(Path path, LinkOption... options) throws IOException
    public static Path setLastModifiedTime(Path path, FileTime time) throws IOException
    public static UserPrincipal getOwner(Path path, LinkOption... options) throws IOException
    public static Path setOwner(Path path, UserPrincipal owner) throws IOException
    public static Set<PosixFilePermission> getPosixFilePermissions(Path path, LinkOption... options) throws IOException
    public static Path setPosixFilePermissions(Path path, Set<PosixFilePermission> perms) throws IOException

    public static Object getAttribute(Path path, String attribute, LinkOption... options) throws IOException
    public static Path setAttribute(Path path, String attribute, Object value, LinkOption... options) throws IOException

    public static <V extends FileAttributeView> V
    getFileAttributeView(Path path, Class<V> type, LinkOption... options)

    public static <A extends BasicFileAttributes> A
    readAttributes(Path path, Class<A> type, LinkOption... options) throws IOException

    public static Map<String,Object>
    readAttributes(Path path, String attributes, LinkOption... options) throws IOException

    //***** ディレクトリの内容を走査 *****
    public static Path
    walkFileTree(Path start, FileVisitor<? super Path> visitor) throws IOException

    public static Path
    walkFileTree(Path start, Set<FileVisitOption> options, int maxDepth, FileVisitor<? super Path> visitor) throws IOException

    public static Stream<Path> walk(Path start, FileVisitOption... options) throws IOException
    public static Stream<Path> walk(Path start, int maxDepth, FileVisitOption... options) throws IOException

    //***** ディレクトリの階層を走査 *****
    public static DirectoryStream<Path> newDirectoryStream(Path dir) throws IOException

    public static DirectoryStream<Path>
    newDirectoryStream(Path dir, DirectoryStream.Filter<? super Path> filter) throws IOException

    public static DirectoryStream<Path> newDirectoryStream(Path dir, String glob) throws IOException

    public static Stream<Path> list(Path dir) throws IOException

    //***** ディレクトリの階層を Stream で走査 *****
    public static Stream<Path>
    find(Path start, int maxDepth, BiPredicate<Path,BasicFileAttributes> matcher, FileVisitOption... options) throws IOException

    //***** MIME Type を調べる *****
    public static String probeContentType(Path path) throws IOException

    //***** FileStore を取得する *****
    public static FileStore getFileStore(Path path) throws IOException
}

次回から Files クラスの各メソッドを見ていきます。 【修正】以前はここに Files クラスのメソッドについての目次を書いてたのですが、前回の記事にまとめて書くことにしました。 ・・・この記事の意味って何?

カテゴリ・クラスとしての Files

java.nio.file パッケージには直接関係ない話ですが、Files クラスの static メソッドのほとんどは第1引数が対象ファイルを表す Path オブジェクトになっているので、Groovy でコーディングする場合は use キーワードでカテゴリとして使うことができます。 これによって Files クラスの static メソッドが Path オブジェクトのインスタンス・メソッドのように使うことができます。 具体例を書くと:

import java.nio.file.Files
import java.nio.file.Paths

use(Files){    // use キーワードで Files クラスをカテゴリに
    def basedir = Paths.get('C:/sample/code/of/java/nio/file')
    basedir.createDirectories()    // 「C:\sample\code\of\java\nio\file」と表示
    assert basedir.isDirectory()

    def path = basedir.resolve('CreateFile.java')
    println path.createFile()    // 「C:\sample\code\of\java\nio\file\CreateFile.java」と表示
    assert path.isRegularFile()
}

ただし、これ以降の記事でのサンプルは(Groovy で書きますが) Java コードが想像できるように書きたいので use キーワードは使いません。

現場で使えるJavaライブラリ

現場で使えるJavaライブラリ