File 类是文件和目录路径名的抽象表示形式,是对文件系统中文件以及目录进行封装后通过面向对象的方式来操作文件和目录。File 类保存文件或目录的各种元数据信息,包括文件名、文件长度、最后修改时间,是否可读、可写,获取当前文件的路径名,判断指定文件是否存在,获得当前目录中的文件列表,创建、删除文件和目录等方法。
构造一个文件对象:
File file = new File("f:" + File.separator + "smile" + File.separator + "silence.txt");
-
File.separator
用来分隔同一路径中的各级目录;而File.pathSeparator
用来分隔多个不同的路径。 -
使用
File.separator
和File.pathSeparator
可以解决跨操作系统的问题。在 UNIX 系统上,File.separator
字段的值为“/”
,File.pathSeparator
字段的值为“:”
;而在 Microsoft Windows 系统上,File.separator
字段的值为“\”
,File.pathSeparator
字段的值为“;”
。
方法名 | 返回值类型 | 描述 |
---|---|---|
getName() | String | 返回此抽象路径名表示的文件或目录的名称 |
getParent() | String | 返回此抽象路径名父目录的路径名字符串;如果此路径名没有指定父目录,则返回 null |
File file = new File("f:" + File.separator + "smile" + File.separator + "silence.txt");
System.out.println(file.getName());
System.out.println(file.getParent());
//输出:
//silence.txt
//f:\smile
创建 File 实例的路径名字符串既可以是绝对路径名也可以是相对路径名。
-
绝对路径名是完整的路径名,不需要任何其他信息就可以定位它所表示的文件。
-
相对路径名必须使用取自其他路径名的信息进行解释。默认情况下,
java.io
包中的类总是根据当前用户目录来解析相对路径名。此目录由系统属性user.dir
指定,通常是 Java 虚拟机的调用目录。
File file = new File("");
System.out.println(file.getAbsolutePath());
System.out.println(System.getProperty("user.dir"));
//输出:
//D:\Git\repository\projects
//D:\Git\repository\projects
方法名 | 返回值类型 | 描述 |
---|---|---|
getPath() | String | 返回此抽象路径名的字符串形式 |
getAbsolutePath() | String | 返回此抽象路径名的绝对路径名字符串 |
getCanonicalPath() | String | 返回此抽象路径名的规范路径名字符串 |
File file1 = new File("f:" + File.separator + "smile" + File.separator + "silence.txt");
System.out.println("file1.getPath() = " + file1.getPath());
System.out.println("file1.getAbsolutePath() = " + file1.getAbsolutePath());
try {
System.out.println("file1.getCanonicalPath() = " + file1.getCanonicalPath());
} catch (IOException e) {
PrintWriter printWriter = new PrintWriter(System.out);
e.printStackTrace(printWriter);
printWriter.flush();
printWriter.close();
}
//输出:
//file1.getPath() = f:\smile\silence.txt
//file1.getAbsolutePath() = f:\smile\silence.txt
//file1.getCanonicalPath() = F:\smile\silence.txt
File file2 = new File("smile" + File.separator + "..\\silence.txt");
System.out.println("file2.getPath() = " + file2.getPath());
System.out.println("file2.getAbsolutePath() = " + file2.getAbsolutePath());
try {
System.out.println("file2.getCanonicalPath() = " + file2.getCanonicalPath());
} catch (IOException e) {
PrintWriter printWriter = new PrintWriter(System.out);
e.printStackTrace(printWriter);
printWriter.flush();
printWriter.close();
}
//输出:
//file2.getPath() = smile\..\silence.txt
//file2.getAbsolutePath() = D:\Git\repository\projects\smile\..\silence.txt
//file2.getCanonicalPath() = D:\Git\repository\projects\silence.txt
注意:getCanonicalPath()
方法返回的规范路径名是绝对路径名,并且是惟一的。规范路径名的准确定义与系统有关。如有必要,此方法首先将路径名转换为绝对路径名,这与调用getAbsolutePath()
方法的效果一样,然后用与系统相关的方式将它映射到其惟一路径名。这通常涉及到从路径名中移除多余的名称(例如"."
和".."
)、解析符号连接(对于 UNIX 平台),以及将驱动器符号(f
)转换为标准大小写形式(F
)(对于 Microsoft Windows 平台)。
方法名 | 返回值类型 | 描述 |
---|---|---|
isAbsolute() | boolean | 测试此抽象路径名是否为绝对路径名 |
System.out.println("file1.isAbsolute() = " + file1.isAbsolute());
System.out.println("file2.isAbsolute() = " + file2.isAbsolute());
//输出:
//file1.isAbsolute() = true
//file2.isAbsolute() = false
方法名 | 返回值类型 | 描述 |
---|---|---|
createNewFile() | boolean | 当且仅当不存在具有此抽象路径名指定名称的文件时,创建一个新的空文件 |
File file1 = new File("f:" + File.separator + "smile" + File.separator + "silence.txt");
try {
System.out.println(file1.createNewFile());
System.out.println(file1.createNewFile());
} catch (IOException e) {
PrintWriter printWriter = new PrintWriter(System.out);
e.printStackTrace(printWriter);
printWriter.flush();
printWriter.close();
}
注意: 当 F 盘不存在 smile 目录时,抛出异常:
java.io.IOException: 系统找不到指定的路径。
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:1012)
at com.mj.wcs.service.impl.FileTestOne.main(FileTestOne.java:18)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
当 F 盘存在 smile 目录时,控制台输出:
true
false
方法名 | 返回值类型 | 描述 |
---|---|---|
mkdir() | boolean | 创建此抽象路径名指定的目录 |
mkdirs() | boolean | 创建此抽象路径名指定的目录,包括所有必需但不存在的父目录 |
File dir1 = new File("f:" + File.separator + "smile");
System.out.println(dir1.mkdir());
//输出:
//true
File dir1 = new File("f:" + File.separator + "smile" + File.separator + "silence");
System.out.println(dir1.mkdir());
//输出:
//false
File dir1 = new File("f:" + File.separator + "smile" + File.separator + "silence");
System.out.println(dir1.mkdirs());
//输出:
//true
注意: mkdir()
方法不能创建多级目录,mkdirs()
方法可以创建多级目录。
方法名 | 返回值类型 | 描述 |
---|---|---|
isFile() | boolean | 测试此抽象路径名表示的文件是否是一个标准文件 |
isDirectory() | boolean | 测试此抽象路径名表示的文件是否是一个目录 |
File file1 = new File("f:" + File.separator + "smile" + File.separator + "silence.txt");
System.out.println(file1.isFile());
System.out.println(file1.isDirectory());
//输出:
//false
//false
try {
if (file1.createNewFile()) {
System.out.println(file1.isFile());
}
} catch (IOException e) {
PrintWriter printWriter = new PrintWriter(System.out);
e.printStackTrace(printWriter);
printWriter.flush();
printWriter.close();
}
//输出:
//true
File dir1 = new File("f:" + File.separator + "smile");
System.out.println(dir1.isFile());
System.out.println(dir1.isDirectory());
//输出:
//false
//true
注意: isFile()
方法当且仅当此抽象路径名表示的文件存在
且是一个标准文件时,返回 true;否则返回 false 。
方法名 | 返回值类型 | 描述 |
---|---|---|
delete() | boolean | 删除此抽象路径名表示的文件或目录。如果此路径名表示一个目录,则该目录必须为空才能删除 |
deleteOnExit() | void | 在虚拟机终止时,请求删除此抽象路径名表示的文件或目录 |
exists() | boolean | 测试此抽象路径名表示的文件或目录是否存在 |
File file1 = new File("f:" + File.separator + "smile" + File.separator + "silence.txt");
File dir1 = new File("f:" + File.separator + "smile");
System.out.println(file1.exists());
System.out.println(file1.delete());
try {
if (dir1.mkdir() && file1.createNewFile()) {
System.out.println(file1.exists());
System.out.println(dir1.delete());
System.out.println(file1.delete());
}
} catch (IOException e) {
PrintWriter printWriter = new PrintWriter(System.out);
e.printStackTrace(printWriter);
printWriter.flush();
printWriter.close();
}
//输出:
//false
//false
//true
//false
//true
注意:
-
当要删除的文件或目录不存在时,
delete()
方法返回 false;当要删除的目录不是空目录时,删除操作失败,delete()
方法返回 false。 -
deleteOnExit()
方法并不立即执行删除操作,只有在虚拟机正常终止时,才会尝试执行删除操作。
方法名 | 返回值类型 | 描述 |
---|---|---|
renameTo(File dest) | boolean | 重新命名此抽象路径名表示的文件 |
File file1 = new File("f:" + File.separator + "smile" + File.separator + "silence.txt");
File file2 = new File("f:" + File.separator + "smile" + File.separator + "smile.txt");
System.out.println(file1.renameTo(file2));
//输出:
//false
try {
if (file1.createNewFile()) {
System.out.println(file1.renameTo(file2));
}
} catch (IOException e) {
PrintWriter printWriter = new PrintWriter(System.out);
e.printStackTrace(printWriter);
printWriter.flush();
printWriter.close();
}
//输出:
//true
try {
if (file1.createNewFile()) {
System.out.println(file1.renameTo(file2));
}
} catch (IOException e) {
PrintWriter printWriter = new PrintWriter(System.out);
e.printStackTrace(printWriter);
printWriter.flush();
printWriter.close();
}
//输出:
//false
File file3 = new File("f:" + File.separator + "smile.txt");
System.out.println(file2.renameTo(file3));
//输出:
//true
注意:
-
当源文件或目录不存在时,
renameTo()
方法返回 false;当目标文件或目录存在时,renameTo()
方法返回 false。 -
当源文件或目录与目标文件或目录属于同一级路径下时,源文件或目录会被重命名为目标文件或目录;当源文件或目录与目标文件或目录不属于同一级路径下时,源文件或目录会被移动到目标文件或目录。
方法名 | 返回值类型 | 描述 |
---|---|---|
canExecute() | boolean | 测试应用程序是否可以执行此抽象路径名表示的文件 |
canRead() | boolean | 测试应用程序是否可以读取此抽象路径名表示的文件 |
canWrite() | boolean | 测试应用程序是否可以修改此抽象路径名表示的文件 |
setExecutable(boolean executable) | boolean | 设置此抽象路径名的所有者的执行权限 |
setExecutable(boolean executable, boolean ownerOnly) | boolean | 设置此抽象路径名的所有者或所有用户的执行权限 |
setReadable(boolean readable) | boolean | 设置此抽象路径名的所有者的读权限 |
setReadable(boolean readable, boolean ownerOnly) | boolean | 设置此抽象路径名的所有者或所有用户的读权限 |
setReadOnly() | boolean | 设置此抽象路径名指定的文件或目录只能进行读操作 |
setWritable(boolean writable) | boolean | 设置此抽象路径名的所有者的写权限 |
setWritable(boolean writable, boolean ownerOnly) | boolean | 设置此抽象路径名的所有者或所有用户的写权限 |
注意: 是否可以删除某个只读文件或目录取决于底层系统。
方法名 | 返回值类型 | 描述 |
---|---|---|
list() | String [ ] | 返回一个字符串数组,这些字符串指定此抽象路径名表示的目录中的文件和目录 |
list(FilenameFilter filter) | String [ ] | 返回一个字符串数组,这些字符串指定此抽象路径名表示的目录中满足指定过滤器的文件和目录 |
listFiles() | File [ ] | 返回一个抽象路径名数组,这些路径名表示此抽象路径名表示的目录中的文件 |
listFiles(FileFilter filter) | File [ ] | 返回抽象路径名数组,这些路径名表示此抽象路径名表示的目录中满足指定过滤器的文件和目录 |
listFiles(FilenameFilter filter) | File [ ] | 返回抽象路径名数组,这些路径名表示此抽象路径名表示的目录中满足指定过滤器的文件和目录 |
File file1 = new File("f:" + File.separator + "smile" + File.separator + "silence.txt");
Optional<String[]> result1 = Optional.ofNullable(file1.list());
System.out.println(result1);
System.out.println("======================================");
File dir1 = new File("f:" + File.separator + "smile");
Optional<String[]> result2 = Optional.ofNullable(dir1.list());
result2.ifPresent(strings -> Arrays.stream(strings).forEach(System.out::println));
System.out.println("======================================");
Optional<String[]> result3 = Optional.ofNullable(
dir1.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith("txt");
}
}));
result3.ifPresent(strings -> Arrays.stream(strings).forEach(System.out::println));
//输出:
//Optional.empty
//======================================
//silence
//silence.log
//silence.txt
//======================================
//silence.txt
注意: 如果此抽象路径名不表示一个目录,那么list()
方法将返回 null。否则将返回一个字符串数组,每个数组元素表示该目录下的文件或子目录名称,而不是完整的路径名。
File 类还有许多其他方法,如下表所示,由于这些方法并不常用,以及篇幅有限的原因,这里就不一一介绍了,感兴趣的朋友可以自己动手实践。
方法名 | 返回值类型 | 描述 |
---|---|---|
length() | long | 返回由此抽象路径名表示的文件的长度 |
isHidden() | boolean | 测试此抽象路径名指定的文件是否是一个隐藏文件 |
lastModified() | long | 返回此抽象路径名表示的文件最后一次被修改的时间 |
setLastModified(long time) | boolean | 设置此抽象路径名指定的文件或目录的最后一次修改时间 |
static listRoots() | File [ ] | 列出可用的文件系统根 |
getTotalSpace() | long | 返回此抽象路径名指定的分区大小,以字节为单位 |
getUsableSpace() | long | 返回此抽象路径名指定的分区上可用于此虚拟机的字节数 |
getFreeSpace() | long | 返回此抽象路径名指定的分区中未分配的字节数 |