//通过使用NIO.2实现递归复制文件目录及文件、子目录,用到了SimpleFileVisitor.
//修改方法中的内容,可实现搜索特定目录下的文件或文件内容。如文件名为一特定值,则反馈文件路径,并结束搜索;递归的加载文件内容,比较,并返回结果。
//List list =
Files.readAllLines(file);
//if (list.toString().indexOf(keyWord) != -1) {
//System.out.println("file.toAbsolutePath():" +
file.toAbsolutePath().toString());
//list.forEach(obj ->
System.out.println(obj));
//}
//this way can be used to seach key words for small text files;
if big file, can use lucene.
import java.io.File;
import java.io.IOException;
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.nio.file.StandardCopyOption;
import
java.nio.file.attribute.BasicFileAttributes;
//Copy file and directory from source to target
recursively using NIO.2
public class CopyFileAndDirectoryRecursivelyUsingNIO2
{
private static String sourcePath =
"D:\\brightmart\\myEclipseWorkspace\\javaCrazy";
private static String targetPath =
"D:\\brightmart\\copy_temp";
public static void main(String[] args) throws Exception {
CopyFileAndDirectoryRecursivelyUsingNIO2 P_X_Test1_ListSubFiles
= new CopyFileAndDirectoryRecursivelyUsingNIO2();
P_X_Test1_ListSubFiles.listSubFileX(sourcePath, targetPath);
}
// use SimpleFileVisitor to copy file and
folders(including all sub folders and sub folder's
file)
public void listSubFileX(String pathName, String
targetString) throws Exception {
Path startPath = Paths.get(pathName);
Path target = Paths.get(targetString);
File fileTarget = target.toFile();
if (!fileTarget.exists()) {
fileTarget.mkdirs();
}
Files.walkFileTree(startPath, new SimpleFileVisitor() {
@Override
public FileVisitResult visitFile(Path file,
BasicFileAttributes attrs) throws IOException {
String fileAbsPath = file.toAbsolutePath().toString();
String subStringOfSource =
fileAbsPath.substring(fileAbsPath.indexOf(pathName) +
pathName.length());
File tempFile = new File(fileTarget,
subStringOfSource);//construct targetFile by combine
Path target = tempFile.toPath();
Files.copy(file, target,
StandardCopyOption.REPLACE_EXISTING);// copy file to target,
replace if existing.
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult preVisitDirectory(Path dir,
BasicFileAttributes attrs) throws IOException {
String dirAbsPath = dir.toAbsolutePath().toString();
String subStringOfSource =
dirAbsPath.substring(dirAbsPath.indexOf(pathName) +
pathName.length());
File tempFile = new File(fileTarget, subStringOfSource);
if (!tempFile.exists() &&
!pathName.equals(subStringOfSource)) {// create directory if not
exists.
tempFile.mkdirs();
}
return FileVisitResult.CONTINUE;
}
});
}
}