1.关于文件夹目录的创建,直接上代码,亮点是方法的嵌套调用
public class Main {
private static String strFilePath = "E:\\kankan";
public static void main(String[] args) {
File file = new File(strFilePath, "aa");
if(!file.exists()){
try {
createDirs(file);
} catch (Exception e) {
e.printStackTrace();
}
}
}
private static void createDirs(File file) {
if(file == null || file.exists()) {
return;
}
createDirs(file.getParentFile());
file.mkdir();
}
}
2.关于指定目录文件的查找,直接上代码了,这个是偶自己写的,亮点是用了FilenameFilter:
package com.ant.test;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;
/**
* @author: antty
* @time:2011-10-31
*/
public class Main {
private static String strFilePath = "E:\\myDropbox\\Dropbox\\Public\\books";
private static String[] bookType = new String[] { "txt", "pdf", "epub" };
public static void main(String[] args) {
getFiles(strFilePath);
for (File file : getFiles(strFilePath)) {
System.out.println(file.getName());
}
}
private static List<File> getFiles(String fileDir) {
List<File> result = new ArrayList<File>();
filtFiles(fileDir, result);
return result;
}
private static void filtFiles(String fileDir, List<File> result) {
File file = new File(fileDir);
File[] files = file.listFiles(new FileFilter());
if (files != null && files.length > 0) {
for (File f : files) {
if (f.isFile()) {
result.add(f);
} else {
filtFiles(f.getAbsolutePath(), result);
}
}
}
}
private static class FileFilter implements FilenameFilter {
public boolean accept(File file, String path) {
File f = new File(file, path);
if (f.isDirectory() && !strFilePath.equals(f.getAbsoluteFile())) {
return true;
}
String ext = getExtension(path);
if (isBookType(ext)) {
return true;
}
return false;
}
private boolean isBookType(String _type) {
for (String type : bookType) {
if (type.equals(_type)) {
return true;
}
}
return false;
}
private String getExtension(String fileName) {
if ((fileName != null) && (fileName.length() > 0)) {
int index = fileName.lastIndexOf('.');
if ((index > 0)) {
return fileName.substring(index + 1).toLowerCase();
}
}
return null;
}
}
}