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


你可能感兴趣的:(java7 NIO2(5) 文件和目录操作API)