Java에서 폴더를 스캔하는 방법은 무엇입니까?
Java에서 재귀 적으로 폴더 내의 모든 파일을 어디에서 어떻게해야합니까?
나무를 어떻게 표현하고 싶은지 잘 모르시겠습니까? 어쨌든 여기에 재귀를 사용하여 전체 하위 트리를 스캔하는 예가 있습니다. 파일과 디렉토리는 동일하게 취급됩니다. 참고 것을 File.listFiles () 반환이 아닌 디렉토리에 대한 널 (null).
public static void main(String[] args) {
Collection<File> all = new ArrayList<File>();
addTree(new File("."), all);
System.out.println(all);
}
static void addTree(File file, Collection<File> all) {
File[] children = file.listFiles();
if (children != null) {
for (File child : children) {
all.add(child);
addTree(child, all);
}
}
}
Java 7은 몇 가지 개선 사항을 제공합니다. 예를 들어 DirectoryStream 은 한 번에 하나의 결과를 제공합니다. 호출자는 더 이상 모든 I / O 작업이 완료 될 때까지 기다릴 필요가 없습니다. 이를 통해 증분 GUI 업데이트, 조기 취소 등이 가능합니다.
static void addTree(Path directory, Collection<Path> all)
throws IOException {
try (DirectoryStream<Path> ds = Files.newDirectoryStream(directory)) {
for (Path child : ds) {
all.add(child);
if (Files.isDirectory(child)) {
addTree(child, all);
}
}
}
}
무시 무시한 null 반환 값이 IOException으로 대체되었습니다.
자바 7은 트리 워커 도 계명 제공합니다 .
static void addTree(Path directory, final Collection<Path> all)
throws IOException {
Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
all.add(file);
return FileVisitResult.CONTINUE;
}
});
}
import java.io.File;
public class Test {
public static void main( String [] args ) {
File actual = new File(".");
for( File f : actual.listFiles()){
System.out.println( f.getName() );
}
}
}
파일과 폴더를 명확하게 표시합니다.
순서를 지정하거나 디렉토리 인쇄 등을 피하려는 파일 클래스의 메소드를 참조하십시오.
http://java.sun.com/javase/6/docs/api/java/io/File.html
Apache Commons FileUtils (listFiles, iterateFiles 등)를 확인하십시오. 원하는 작업을 수행하고 필터를 적용 할 수있는 편리한 방법입니다.
http://commons.apache.org/io/api-1.4/org/apache/commons/io/FileUtils.html
FileFilter
인터페이스를 사용하여 원하는 것을 필터링 할 수 있습니다 . 이를 구현하는 익명 클래스를 만들 때 가장 잘 사용됩니다.
import java.io.File;
import java.io.FileFilter;
public class ListFiles {
public File[] findDirectories(File root) {
return root.listFiles(new FileFilter() {
public boolean accept(File f) {
return f.isDirectory();
}});
}
public File[] findFiles(File root) {
return root.listFiles(new FileFilter() {
public boolean accept(File f) {
return f.isFile();
}});
}
}
public static void directory(File dir) {
File[] files = dir.listFiles();
for (File file : files) {
System.out.println(file.getAbsolutePath());
if (file.listFiles() != null)
directory(file);
}
}
다음 dir
은 스캔 할 디렉토리입니다. 예 :c:\
트리 구조를 구축하는 것이 가장 편리한 방법.
public static void main(String[] args) throws IOException {
printTree(0, new File("START/FROM/DIR"));
}
static void printTree(int depth, File file) throws IOException {
StringBuilder indent = new StringBuilder();
String name = file.getName();
for (int i = 0; i < depth; i++) {
indent.append(".");
}
//Pretty print for directories
if (file.isDirectory()) {
System.out.println(indent.toString() + "|");
if(isPrintName(name)){
System.out.println(indent.toString() + "*" + file.getName() + "*");
}
}
//Print file name
else if(isPrintName(name)) {
System.out.println(indent.toString() + file.getName());
}
//Recurse children
if (file.isDirectory()) {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++){
printTree(depth + 4, files[i]);
}
}
}
//Exclude some file names
static boolean isPrintName(String name){
if (name.charAt(0) == '.') {
return false;
}
if (name.contains("svn")) {
return false;
}
//.
//. Some more exclusions
//.
return true;
}
JDK7에서 "더 많은 NIO 기능"은 파일 트리 또는 디렉토리를 적용하는 내용에 방문자 패턴을 가져옵니다. 대규모 파일이 없습니다.
참고 URL : https://stackoverflow.com/questions/189094/how-to-scan-a-folder-in-java
'ProgramingTip' 카테고리의 다른 글
-fembed-bitcode는 iOS 6.0 이전 버전에서 지원되지 않습니다. (0) | 2020.12.11 |
---|---|
힙 대신 스택을 사용하는 것이 가장 좋은 언제입니까? (0) | 2020.12.11 |
데이터베이스 설계 모범 사례 (0) | 2020.12.11 |
SQL Server 2008에서 열 값을 어떻게 바꾸나요? (0) | 2020.12.11 |
C # 사전에 대한 명명 규칙 (0) | 2020.12.11 |