java项目实践一:目录文件遍历
能实现指定目录下指定类型的文件遍历
package util;
import java.io.File;
import java.io.IOException;
/* INPUT: directory, file type
* OUTPUT: file names of file type
*/
public class test{
public static void main(String[] args) throws IOException {
util.listDirectory(new File("D:\\Hallieping\\documents\\新文献\\fake news"), ".pdf");
}
} package util;
// java实践1 遍历目录
import java.io.File;
import java.io.IOException;
public class util {
public static void listDirectory(File dir, String fileType) throws IOException {
if( !dir.exists())
throw new IllegalArgumentException("The directory :" + dir +" doesn't exist.");
if( !dir.isDirectory())
throw new IllegalArgumentException( dir + "is not a directory !");
File[] list = dir.listFiles();
// list all files including directories in dir;
if(list != null && list.length > 0) {
for(File file: list) {
if(file.isDirectory()) {
listDirectory(file, fileType);
// if it is a sub-directory, recur;
}
else {
if(file.isFile() && file.getName().endsWith(fileType)) {// print the right files' names;
System.out.println(file.getName());
}
}
}
}
}
} 细节错误:
1.方法 throws IOException{}
内部 throw ...Exception
2.printlin 全小写
3.文件全都放在package util下面,并且都在src下面
基恩士成长空间 426人发布
查看9道真题和解析