java NIO2(file io)のサンプルクラス

1.Pathオブジェクトを作成
Path p1 = Paths.get(“/tmp/foo");
Path p2 = Paths.get(filename);
Path p3 = Paths.get(URI.create(“C://File.java"));

2.Path オブジェクトの情報を取得
Path path = Paths.get(“D:\\Program Files\\Java\\text.txt");
System.out.format(“toString: %s%n", path.toString());
//D:\Program Files\Java\text.txt
System.out.format(“getFileName: %s%n", path.getFileName());
//startnewste.txt
System.out.format(“getName(0): %s%n", path.getName(0));
//Program Files
System.out.format(“getNameCount: %d%n", path.getNameCount());
//3
System.out.format(“subpath(0,2): %s%n", path.subpath(0,2));
// Program Files\Java
System.out.format(“getParent: %s%n", path.getParent());
// D:\Program Files\Java
System.out.format(“getRoot: %s%n", path.getRoot());
//D:\

3.Pathの変換

3.1 Pathをuriに変換
Path path = Paths.get(“\\Java\\text.txt");
System.out.format(“%s%n", path.toUri());
//出力:file:///I:/Java/text.txt

3.2 toAbsolutePathで絶対パスに変換
Path path = Paths.get(“\\Java\\text.txt");
System.out.format(“%s%n", path.toAbsolutePath());
//出力:I:\Java\text.txt

3.3 toFile()でファイルに変換
Path path = Paths.get(“D:\\Program Files\\Java\\text.txt");
File filePath = path.toFile();
System.out.format(“%s%n",filePath);
System.out.format(“fileExist? %b%n",filePath.exists());
//出力:D:\Program Files\Java\text.txt

4.複数のpathを連結
4.1
Path path = Paths.get(“D:\\Program Files\\Java");
System.out.format(“%s%n",path.resolve(“other.txt"));
//出力:D:\Program Files\Java\other.txt

4.2
Path path = Paths.get(“java").resolve(“D:\\Program Files");
System.out.format(“%s%n",path);
//出力:D:\Program Files

5.
Path p1 = Paths.get(“jdk1.7.0_40");
Path p2 = Paths.get(“java");
Path p1_to_p2 = p1.relativize(p2);//..\java
Path p2_to_p1 = p1_to_p2.relativize(p1);//..\..\jdk1.7.0_40

6.2つのpathを比較
Path path = …;
Path otherPath = …;
Path beginning = Paths.get(“/home");
Path ending = Paths.get(“java");
if (path.equals(otherPath)) {
} else if (path.startsWith(beginning)) {

} else if (path.endsWith(ending)) {

}

Java

Posted by arkgame