赞
踩
java.io.File
类是 Java IO 包中用于表示文件或目录路径的类。它提供了许多方法,用于操作文件和目录的属性、路径、名称等信息,但它并不提供用于文件内容读写的方法,这些读写操作通常通过其他类来完成。
以下是 java.io.File
类的一些常用方法:
创建文件或目录:
boolean createNewFile()
:创建一个新的空文件。boolean mkdir()
:创建一个新的目录。删除文件或目录:
boolean delete()
:删除文件或目录。获取文件或目录信息:
String getName()
:获取文件或目录的名称。String getPath()
:获取文件或目录的路径。String getAbsolutePath()
:获取文件或目录的绝对路径。long length()
:获取文件的长度(字节数)。boolean isFile()
:判断是否为文件。boolean isDirectory()
:判断是否为目录。boolean exists()
:判断文件或目录是否存在。遍历目录:
String[] list()
:返回目录中所有文件和子目录的名称数组。File[] listFiles()
:返回目录中所有文件和子目录的 File
对象数组。其他方法:
boolean renameTo(File dest)
:重命名文件或目录。boolean canRead()
:判断文件是否可读。boolean canWrite()
:判断文件是否可写。boolean setReadOnly()
:将文件设置为只读。java.io.File
类提供了一种便捷的方式来操作文件和目录的属性和信息,它与平台无关,可以在不同的操作系统上使用。但需要注意的是,它只是一个路径名的抽象表示,并不代表文件本身的内容。因此,要读取或写入文件内容,需要使用其他 IO 类(如 FileInputStream
、FileOutputStream
、BufferedReader
、BufferedWriter
等)。
- import java.io.File;
- import java.io.IOException;
-
- public class Main {
- public static void main(String[] args) {
- // 创建 File 对象表示文件或目录
- File file = new File("example.txt");
- File directory = new File("exampleDir");
-
- try {
- // 创建文件
- if (file.createNewFile()) {
- System.out.println("File created: " + file.getAbsolutePath());
- } else {
- System.out.println("File already exists.");
- }
-
- // 创建目录
- if (directory.mkdir()) {
- System.out.println("Directory created: " + directory.getAbsolutePath());
- } else {
- System.out.println("Directory already exists.");
- }
-
- // 输出文件和目录信息
- System.out.println("File name: " + file.getName());
- System.out.println("File path: " + file.getPath());
- System.out.println("File absolute path: " + file.getAbsolutePath());
- System.out.println("File length: " + file.length() + " bytes");
- System.out.println("Is file: " + file.isFile());
- System.out.println("Is directory: " + file.isDirectory());
-
- System.out.println("Directory name: " + directory.getName());
- System.out.println("Directory path: " + directory.getPath());
- System.out.println("Directory absolute path: " + directory.getAbsolutePath());
- System.out.println("Is file: " + directory.isFile());
- System.out.println("Is directory: " + directory.isDirectory());
-
- // 删除文件和目录
- if (file.delete()) {
- System.out.println("File deleted: " + file.getAbsolutePath());
- } else {
- System.out.println("Failed to delete file.");
- }
-
- if (directory.delete()) {
- System.out.println("Directory deleted: " + directory.getAbsolutePath());
- } else {
- System.out.println("Failed to delete directory.");
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。