File
类的对象是文件或目录的路径名的抽象表示。
创建文件
我们可以从以下创建一个File
对象 -
- 一个路径名
- 一个父路径名和子路径名
- 一个URI (统一资源标识符)
可以使用File
类的以下构造函数之一来创建一个文件:
File(String pathname)
File(File parent, String child)
File(String parent, String child)
File(URI uri)
如果有一个文件路径文件名称的字符串为test.txt
,可以创建一个抽象路径名称,如下面的代码。
File dummyFile = new File("test.txt");
名称为test.txt
的文件不必存在,以使用此语句创建File
对象。dummyFile
对象表示抽象路径名,它可指向或可能不指向文件系统中的真实文件。
File
类有几个方法来处理文件和目录。使用File
对象可以创建新文件,删除已存在的文件,重命名文件,更改文件权限等。
File
类中的isFile()
和isDirectory()
告诉File
对象是否表示文件或目录。
当前工作目录
JVM的当前工作目录是根据运行java命令来设置的。可以通过读取user.dir
系统属性来获取JVM的当前工作目录,如下所示:
String workingDir = System.getProperty("user.dir");
使用System.setProperty()
方法更改当前工作目录。
System.setProperty("user.dir", "C:\\myDir");
要在Windows上指定C:\test
作为user.dir
系统属性值,运行如下所示的程序:
java -Duser.dir=C:\test your-java-class
检查文件是否存在
可以使用File
类的exists()
方法检查File
对象的抽象路径名是否存在。
boolean fileExists = dummyFile.exists();
完整源代码如下 -
import java.io.File;
public class Main {
public static void main(String[] argv) {
// Create a File object
File dummyFile = new File("dummy.txt");
// Check for the file's existence
boolean fileExists = dummyFile.exists();
if (fileExists) {
System.out.println("The dummy.txt file exists.");
} else {
System.out.println("The dummy.txt file does not exist.");
}
}
}
上面的代码生成以下结果。
The dummy.txt file does not exist.
路径
绝对路径是在文件系统上唯一标识文件。使用规则路径是唯一标识文件系统上文件的最简单路径。可以使用getAbsolutePath()
和getCanonicalPath()
方法来分别获得由File
对象表示的绝对路径和规范路径。
import java.io.File;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
printFilePath("dummy.txt");
printFilePath(".." + File.separator + "notes.txt");
}
public static void printFilePath(String pathname) {
File f = new File(pathname);
System.out.println("File Name: " + f.getName());
System.out.println("File exists: " + f.exists());
System.out.println("Absolute Path: " + f.getAbsolutePath());
try {
System.out.println("Canonical Path: " + f.getCanonicalPath());
}
catch (IOException e) {
e.printStackTrace();
}
}
}
上面的代码生成以下结果。
File Name: dummy.txt
File exists: false
Absolute Path: F:\WebSite\Yiib\worksp\SingletonPattern\dummy.txt
Canonical Path: F:\WebSite\Yiib\worksp\SingletonPattern\dummy.txt
File Name: notes.txt
File exists: false
Absolute Path: F:\WebSite\Yiib\worksp\SingletonPattern\..\notes.txt
Canonical Path: F:\WebSite\Yiib\worksp\notes.txt
文件分隔符
不同的操作系统使用不同的字符来分隔路径名中的两个部分。例如,Windows在路径名中使用反斜杠(\
)作为名称分隔符,而UNIX使用正斜杠(/
)。
File
类定义了一个名称为分隔符Char
的常量,它是系统相关的名称分隔符。可以使用File.separator
字符常量作为分隔符。File.separator
常量名称作为String
分隔符。
在程序中使用名称分隔符(File.separator
)使Java代码在不同的平台上工作。