File.listFiles,100万个文件,大概1200毫秒 Path和Files的写法,大概900毫秒。
import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.nio.file.DirectoryStream; 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.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.List;
public class ListFileName {
public static void main(String[] args) {
String path = args[0]; String type = args[1]; if (type.equals("1")) { test1(path); } else if (type.equals("2")) { test2(path); } else if (type.equals("3")) { test2(path); } }
public static void test1(String path) { long a = System.currentTimeMillis(); File[] files = new File(path).listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return !name.endsWith(".md5") && !name.endsWith(".tmp") && !name.startsWith("."); } }); System.out.println("文件数量:" + files.length); long b = System.currentTimeMillis(); System.out.println("毫秒:" + (b - a)); }
public static void test2(String path) { long a = System.currentTimeMillis();
List<String> list = new ArrayList<>(); try { Path directory = Paths.get(path); try (DirectoryStream<Path> stream = Files.newDirectoryStream(directory)) { for (Path file : stream) { list.add(file.getFileName().toString()); } } catch (IOException e) { e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } System.out.println("文件数量:" + list.size()); long b = System.currentTimeMillis(); System.out.println("毫秒:" + (b - a)); } public static void test3(String path) { long a = System.currentTimeMillis();
Path directory = Paths.get(path); final List<String> list = new ArrayList<>(); try { Files.walkFileTree(directory, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { list.add(file.getFileName().toString()); return FileVisitResult.CONTINUE; }
@Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { return FileVisitResult.SKIP_SUBTREE; }
@Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { return FileVisitResult.CONTINUE; } }); } catch (IOException e) { e.printStackTrace(); } System.out.println("文件数量:" + list.size()); long b = System.currentTimeMillis(); System.out.println("毫秒:" + (b - a)); }
}
|