Java traverse directory

a code implementation
package com.imooc.io;
import java.io.IOException;
import java.io.File;
 
//List some common operations of File such as filtering, traversal, etc.
public class FileUtils {
//List all files in the specified directory (including subdirectories)
public static void listDirectory(File dir)throws IOException{
if(!dir.exists()){
throw new IllegalArgumentException("directory"+dir+"does not exist");
}
if(!dir.isDirectory()){
throw new IllegalArgumentException(dir+"is not a directory");
}
/*String[] filenames = dir.list();//The returned string array does not contain the contents of subdirectories
for(String name:filenames){
System.out.println(dir+"\\"+name);
}*/
 
//If you want to traverse the contents of the subdirectory, you need to construct a File object for recursive operation. File provides an API that directly returns the File object
File[] files = dir.listFiles();//Returns the abstraction of direct subdirectories (files)
if(files!=null&&files.length>0){
for(File file:files){
if(file.isDirectory()){
//recursive
listDirectory(file);
}
else{
System.out.println(file);
}
}
}
}
}
 
Two test classes
package com.imooc.io;
import java.io.File;
import java.io.IOException;
public class FileUtiltest1 {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
FileUtils.listDirectory(new File("E:\\Hadoop"));
}
}
 
Three realization effects
E:\Hadoop\556fccbb00019d7b00000000.rar
E:\Hadoop\Chapter 5 - Code\5-1\WordCount.java
E:\Hadoop\Chapter 5 - Code\5-2\Sort.java

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326696228&siteId=291194637