Filesクラスを用いたファイル操作
前回からの続編ということで、Java7のjava.nio.file.Filesクラスを利用した各種ファイル操作をメモとして残します。
今回はFilesクラスによる基本的なディレクトリ、ファイルの作成、コピー、削除を紹介します。(まあ、自分用のメモですが。)
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { Path testDirPath = FileSystems.getDefault().getPath("path_to_dir"); try { // ディレクトリ作成 Files.createDirectory(testDirPath); if (Files.exists(testDirPath)) { System.out.println("Created the directory."); } else { System.out.println("Failed creating the direcotry"); System.exit(1); } // ファイル作成 Path newFilePath = FileSystems.getDefault().getPath(testDirPath.toString() + "/hoge.txt"); Files.createFile(newFilePath); if (Files.exists(newFilePath)) { System.out.println("Created the new file."); } else { System.out.println("Failed creating the new file."); System.exit(1); } // ファイルにデータを書き込む List<String> contents = new ArrayList<>(); contents.add("hoge1"); contents.add("hoge2"); contents.add("hoge3"); try (BufferedWriter bw = Files.newBufferedWriter(newFilePath, StandardCharsets.UTF_8)) { for (String s : contents) { bw.write(s + "\n"); } } // ファイルのコピー Path copiedFilePath = FileSystems.getDefault().getPath(testDirPath.toString() + "/copiedHogeFile.txt"); Files.copy(newFilePath, copiedFilePath); if (Files.exists(copiedFilePath)) { System.out.println("Copied hoge.txt to copiedHogeFile.txt"); } else { System.out.println("Failed copying hoge.txt"); System.exit(1); } // コピーしたファイルの内容を出力 System.out.println("----- The contents of " + copiedFilePath.getFileName() + " -----"); try (BufferedReader br = Files.newBufferedReader(copiedFilePath, StandardCharsets.UTF_8)) { String line; while ((line = br.readLine()) != null) { System.out.println(line); } } System.out.println("----- end -----"); // 作成したhoge.txtファイルの削除 Files.delete(newFilePath); if (!Files.exists(newFilePath)) { System.out.println("Deleted hoge.txt."); } else { System.out.println("Failed deleting hoge.txt."); System.exit(1); } // コピーしたcopiedHogeFile.txtファイルの削除 Files.delete(copiedFilePath); if (!Files.exists(copiedFilePath)) { System.out.println("Deleted copiedHogeFile.txt."); } else { System.out.println("Failed deleting copiedHogeFile.txt."); System.exit(1); } // 作成したディレクトリの削除 Files.delete(testDirPath); if (!Files.exists(testDirPath)) { System.out.println("Deleted the directory."); } else { System.out.println("Failed deleting the direcotry"); System.exit(1); } } catch (IOException e) { e.printStackTrace(); } } }
FileSystems.getDefault().getPath("path_to_dir")で対象ディレクトリのPathオブジェクトを取得します。path_to_dirは適当に読み替えてください。
【ディレクトリの作成】
ディレクトリの作成はFilesクラスのcreateDirectoryメソッドに最初に取得したディレクトリのPathオブジェクトを渡し、実行します。サブディレクトリも含めたディレクトリの作成を行うときは、サブディレクトリも含めたPathオブジェクトを作成しcreateDirectoriesメソッドを実行します。
【ファイルの作成】
ファイルの作成はFilesクラスのcreateFileメソッドに作成するファイルパスを設定したPathオブジェクトを渡し、実行します。
【ファイルのコピー】
Filesクラスのcopyメソッドで行います。第一引数にコピー元のPathを、第二引数にコピー先のPathを渡します。なお、このメソッドはInputStreamからのコピーや、OutputStreamへのコピーも可能なようです。
たとえばInputStreamからのコピーの場合、第一引数にInputStreamオブジェクトを設定します。OutputStreamへのコピーの場合は第二引数にOutputStreamオブジェクトを設定します。
【ファイル/ディレクトリの削除】
ファイルとディレクトリの削除はともにdeleteメソッドに削除したいファイル/ディレクトリのPathオブジェクトを渡して実行します。対象が存在している場合のみ削除する場合はdeleteIfExistsメソッドを利用します。
Files.existsは言うまでもなく存在チェックなので割愛します。
やはりJava7でのファイル操作に慣れるともう昔に戻れなくなるというか、便利です。Filesクラスにはこれ以外にもシンボリックリンクを作成するメソッドや、テンポラリファイルを作成するメソッドなどがありますが、それらについては機会があれば載せてみます。