作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想扫描电脑中的所有磁盘以查找记事本(.txt)文件并将它们复制到新创建的目录中。怎么做 ?如果可能的话,跳过C下的一些文件夹,例如Windows。目前我只能扫描特定目录。
谢谢
public void scanFolder(int depth, File file) {
StringBuilder indent = new StringBuilder();
String name = file.getName();
String extension;
String txtcheck = "txt";
;
for (int i = 0; i < depth; i++) {
indent.append(".");
}
//Pretty print for directories
if (file.isDirectory()) {
String seperator = indent.toString() + "|";
if (isPrintName(name)) {
}
}
//Print file name
else if (isPrintName(name)) {
out2 = indent.toString() + file.getName();
extension = name.substring(name.lastIndexOf(".") + 1, name.length());
if (txtcheck.equals(extension)) {
outs.add(out2);
}
}
if (file.isDirectory()) {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
scanFolder(depth + 4, files[i]);
}
}
}
scanFolder(0, new File("C:\\lefdef"));
最佳答案
我已经这样做了,下面是答案代码;
import java.io.*;
import java.nio.file.*;
import java.nio.file.attribute.*;
import static java.nio.file.FileVisitResult.*;
import javax.swing.filechooser.FileSystemView;
public class Find {
private static int finalTotal = 0;
public static class Finder
extends SimpleFileVisitor<Path> {
private final PathMatcher matcher;
private int numMatches = 0;
Finder(String pattern) {
matcher = FileSystems.getDefault()
.getPathMatcher("glob:" + pattern);
}
// Compares the glob pattern against
// the file or directory name.
void find(Path file) {
Path name = file.getFileName();
if (name != null && matcher.matches(name)) {
numMatches++;
System.out.println(file);
}
}
// Prints the total number of
// matches to standard out.
void done() {
System.out.println("Matched: "
+ numMatches);
finalTotal = finalTotal + numMatches;
}
// Invoke the pattern matching
// method on each file.
@Override
public FileVisitResult visitFile(Path file,
BasicFileAttributes attrs) {
find(file);
return CONTINUE;
}
// Invoke the pattern matching
// method on each directory.
@Override
public FileVisitResult preVisitDirectory(Path dir,
BasicFileAttributes attrs) {
find(dir);
return CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file,
IOException exc) {
// System.err.println(exc);
return CONTINUE;
}
}
public static void main(String[] args)
throws IOException {
File[] paths;
FileSystemView fsv = FileSystemView.getFileSystemView();
paths = File.listRoots();
for (File path : paths) {
String str = path.toString();
String slash = "\\";
String s = new StringBuilder(str).append(slash).toString();
Path startingDir = Paths.get(s);
String pattern = "*.txt";
Finder finder = new Finder(pattern);
Files.walkFileTree(startingDir, finder);
finder.done();
}
System.out.println("Total Matched Number of Files : " + finalTotal);
}
}
关于java - 如何在Java中扫描所有驱动器以查找特定文件扩展名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22527814/
我是一名优秀的程序员,十分优秀!