用途
File类用于表示目录或文件,只是描述目录或文件的信息,不能用于访问文件的内容。
常用方法
- boolean mkdir();
- boolean mkdirs();
- boolean createNewFile();
- boolean delete()
public void createDir(String dirPath) {
File file = new File(dirPath);
if (!file.exists()) {
file.mkdir();
} else {
file.delete();
}
}
- boolean canExecute()
- boolean canRead()
- boolean canWrite()
- boolean exists()
- boolean isDirectory()
- boolean isFile()
- boolean isHidden()
- boolean isAbsolute()
- String getName()
- String getPath()
- String getAbsolutePath()
- String getParent()
- long lastModified()
- long length()
- boolean renameTo(File f)
- File[] listFiles()
/**
* @param dirPath
* 列出所有的文件及子目录下文件
*/
public void listAllFile(String dirPath) {
File file = new File(dirPath);
if (!file.exists() || !file.isDirectory()) {
System.out.println(dirPath + "is not exist or it's not a dir.");
return;
}
listFiles(file);
}
public void listFiles(File currentFile) {
if (!currentFile.exists()) {
return;
}
File[] files = currentFile.listFiles();
for (File file: files) {
if (file.isDirectory()) {
listFiles(file);
} else {
System.out.println(file);
}
}
}
- String[] list()
- String[] list(FilenameFilter filter)
这两个方法返回的字符串数组,数组的内容是当前file路径下的文件或子目录名,如果file是个文件,则返回null;
对于第二个方法,需要一个实现了FilenameFilter接口的类实例;
public interface FilenameFilter {
boolean accept(File dir, String name);
}
这是一个典型的策略模式,在list中会调用filter的accept()方法,如果accept()返回的是true,这个文件或者目录就会包含在list()方法的返回值中。