1. 程式人生 > >java7 NIO2(5) 檔案和目錄操作API

java7 NIO2(5) 檔案和目錄操作API

java7 NIO2使用walk遞迴介面遞迴操作檔案,可以使用這個介面進行檔案搜尋,檔案內容搜尋,遞迴拷貝,遞迴移動,遞迴刪除等操作。

package com.mime;

import java.io.IOException;
import java.nio.file.FileVisitOption;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.util.EnumSet;

public class NIO2FileWalk {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Path listDir = Paths.get("/tmp"); // define the starting file
		//
		ListTree walk = new ListTree();
		try {
			Files.walkFileTree(listDir, walk);
		} catch (IOException e) {
			System.err.println(e);
		}

		//遍歷的時候跟蹤連結
		EnumSet opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS); 
		try {
			Files.walkFileTree(listDir, opts, Integer.MAX_VALUE, walk); 
		} catch (IOException e) {
			System.err.println(e);
		}
		
		//FileVisitor 提供perform a file search, a recursive copy, arecursive move, and a recursive delete.

	}

}

// NIO2 遞迴遍歷檔案目錄的介面實現
class ListTree extends SimpleFileVisitor<Path> {
	@Override
	public FileVisitResult postVisitDirectory(Path dir, IOException exc) {
		System.out.println("Visited directory: " + dir.toString());
		return FileVisitResult.CONTINUE;
	}

	@Override
	public FileVisitResult visitFileFailed(Path file, IOException exc) {
		System.out.println(exc);
		return FileVisitResult.CONTINUE;
	}
}

輸出:
Visited directory: /tmp/.ICE-unix
Visited directory: /tmp/gpg-LOz0cL
Visited directory: /tmp/.org.chromium.Chromium.YKWsQJ
Visited directory: /tmp/hsperfdata_weijianzhongwj
Visited directory: /tmp/kde-weijianzhongwj
java.nio.file.AccessDeniedException: /tmp/pulse-qKcxuRTsGUob
Visited directory: /tmp/ksocket-weijianzhongwj
Visited directory: /tmp/nio_5078970948266789689
Visited directory: /tmp/pulse-j0jluTvI3Pe6
Visited directory: /tmp/3892364837850046417
Visited directory: /tmp/sni-qt_kaccessibleapp_2026-mEz8Dy/icons/hicolor/22x22/apps
Visited directory: /tmp/sni-qt_kaccessibleapp_2026-mEz8Dy/icons/hicolor/22x22
Visited directory: /tmp/sni-qt_kaccessibleapp_2026-mEz8Dy/icons/hicolor
Visited directory: /tmp/sni-qt_kaccessibleapp_2026-mEz8Dy/icons
Visited directory: /tmp/sni-qt_kaccessibleapp_2026-mEz8Dy
Visited directory: /tmp/.X11-unix
Visited directory: /tmp/akonadi-weijianzhongwj.mjmToI
Visited directory: /tmp/ssh-mfuayNh73d7Q
Visited directory: /tmp/aaa/bbb/ccc
Visited directory: /tmp/aaa/bbb
Visited directory: /tmp/aaa
java.nio.file.AccessDeniedException: /tmp/pulse-PKdhtXMmr18n
Visited directory: /tmp