File:An abstract representation of file and directory pathnames. 文件和文件夹路径名的抽象表示。
(1)创建文件
例:在指定目录下,创建一个文件(File):
public static void main(String[] args)
{
// File file = new File("E:/sailang/lizhongyi.doc");
// File file = new File("E:/sailang");
// File file2 = new File(file, "lizhongyi.txt");
File file = new File("E:/sailang", "lizhongyi.doc");
try
{
System.out.println(file.createNewFile());
}
catch (IOException e)
{
e.printStackTrace();
}
}
creatNewFile() 只能创建文件,需要注意的是,在创建文件时,文件所在目录结构必须已经存在,否则会报错!
补充:
在windows操作系统中,目录结构为:E:\sailang。其中使用的反斜杠\,但是在Java中,\是被用作转意字符的, 因此,这种目录结构不能够直接作为File()的参数,有两种解决方法:
- E:\\sailang
- E:/sailang 这种方法在多数操作系统中都适应,因此,一般选用这种!
(2)创建目录
File file = new File("E:/sailang/lizhongyi");
file.mkdir();
采用mkdir方法创建lizhongyi子目录时,其前面的目录必须都已经存在!
而mkdirs() 可以把所有的子目录都可以创建出来!
isFile:Tests whether the file denoted by this abstract pathname is a normal file.
isDirectory:Tests whether the file denoted by this abstract pathname is a directory.
mkdir:Creates the directory named by this abstract pathname.
mkdirs:Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories.
(3)返回指定目录下所包含的文件或者子目录的名字
list:Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname.
File file = new File("E:/sailang");
if(file.mkdirs() == false)
{
String[] names = file.list();
for(String name : names)
{
System.out.println(name);
}
}
(4)FilenameFilter
这个类在《设计模式之策略模式》中有,是最后一个例子,大家想看的可以看看!
(5)以树形结构展现目录以及其内部的文件
代码参见《如何编写递归程序》