java.io.File类包含两个方法,我们可以使用它们来确定文件是目录还是java中的常规文件。
isFile()
: 如果文件存在并且是普通文件,则此方法返回true,注意如果文件不存在则返回false。isDirectory()
: 如果文件实际上是目录,则此方法返回 true,如果路径不存在,则返回 false。
在检查文件是目录还是普通文件时,首先要检查文件是否存在。如果它存在,那么只有我们应该检查它是目录还是文件。
一个简单的java程序显示它的用法。
package com.journaldev.files;
import java.io.File;
public class CheckDirectoryOrFile {
public static void main(String[] args) {
File file = new File("/Users/pankaj/source.txt");
File dir = new File("/Users/pankaj");
File notExists = new File("/Users/pankaj/notafile");
System.out.println("/Users/pankaj/source.txt is file?"+file.isFile());
System.out.println("/Users/pankaj/source.txt is directory?"+file.isDirectory());
System.out.println("/Users/pankaj is file?"+dir.isFile());
System.out.println("/Users/pankaj is directory?"+dir.isDirectory());
System.out.println("/Users/pankaj/notafile is file?"+notExists.isFile());
System.out.println("/Users/pankaj/notafile is directory?"+notExists.isDirectory());
}
}
上述程序的输出为:
/Users/pankaj/source.txt is file?true
/Users/pankaj/source.txt is directory?false
/Users/pankaj is file?false
/Users/pankaj is directory?true
/Users/pankaj/notafile is file?false
/Users/pankaj/notafile is directory?false