Last active
September 30, 2022 15:23
-
-
Save atsushi-kitazawa/e74c99e399774e7fd517732479887765 to your computer and use it in GitHub Desktop.
file list example by FileVisitor.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.File; | |
import java.io.FilenameFilter; | |
import java.io.IOException; | |
import java.nio.file.FileVisitOption; | |
import java.nio.file.FileVisitResult; | |
import java.nio.file.FileVisitor; | |
import java.nio.file.Files; | |
import java.nio.file.Path; | |
import java.nio.file.Paths; | |
import java.nio.file.attribute.BasicFileAttributes; | |
import java.util.ArrayList; | |
import java.util.EnumSet; | |
import java.util.List; | |
public class Main { | |
public static void main(String[] args) { | |
if (args.length == 0) { | |
System.exit(-1); | |
} | |
String root = args[0]; | |
printMemoryInfo(); | |
do1(root); | |
// do2(root); | |
printMemoryInfo(); | |
} | |
private static void do1(String root) { | |
Path path = Paths.get(root); | |
try { | |
FileVisitorImple fv = new FileVisitorImple(); | |
Files.walkFileTree(path, EnumSet.noneOf(FileVisitOption.class), 1, fv); | |
System.out.println("file count " + fv.getFiles().size()); | |
for (String f : fv.getFiles()) { | |
// System.out.println(f); | |
} | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
private static void do2(String root) { | |
File dir = new File(root); | |
File[] files = dir.listFiles(new FilenameFilter() { | |
@Override | |
public boolean accept(File dir, String name) { | |
return true; | |
} | |
}); | |
System.out.println("file count " + files.length); | |
for (File f : files) { | |
// System.out.println(f); | |
} | |
} | |
private static void printMemoryInfo() { | |
System.out.println(Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()); | |
} | |
} | |
class FileVisitorImple implements FileVisitor<Path> { | |
private List<String> files = new ArrayList<>(); | |
public List<String> getFiles() { | |
return files; | |
} | |
@Override | |
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { | |
return FileVisitResult.CONTINUE; | |
} | |
@Override | |
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { | |
String fileName = file.getFileName().toString(); | |
files.add(fileName); | |
return FileVisitResult.CONTINUE; | |
} | |
@Override | |
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { | |
return FileVisitResult.CONTINUE; | |
} | |
@Override | |
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { | |
return FileVisitResult.TERMINATE; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment