java中File类

发布于:2024-12-18 ⋅ 阅读:(56) ⋅ 点赞:(0)

1、介绍

File类定义了一些与平台无关的方法来操作文件,可以通过调用File类中的方法,实现创建、删除、重命名文件等操作。File类的对象主要用来获取文件本身的一些信息,如文件所在的目录、文件长度、文件读写权限等。数据流可以将数据写入到文件中,文件也是数据流最常用的数据媒体。

2、文件的创建与删除

使用File类创建一个文件对象。通常使用以下3种构造方法来创建文件对象。

一、File(String pathname)

该构造方法通过将给定路径名字字符串转换为抽象路径名来创建一新File实例。

语法:new File(String pathname)

其中,pathname指路径名称(包含文件名)

语法:File file=new File("d:/1.txt");

二、File(String parent,String child)

该构造方法根据定义的父路径和子路径字符串(包含文件名)创建一个新的File对象。

语法:new File(String parent,String child)

parent:父路径字符串,如D:/或D:/doc/

child:子路径字符串,如letter.txt

三、File(File f,String child)

该构造方法根据parent抽象路径名和child路径名字符串创建一个新File实例。

语法:new File(File f,String child)

f:父路径对象,列如D:/doc/

child:子路径字符串,如letter.txt

2.1 程序代码(列子)
import java.io.File;

/**
 * 这是一个测试文件操作的Java程序,用于检查、创建或删除文件。
 */
public class FileTest {

    public static void main(String[] args) {
        // 创建一个File对象,代表当前目录下的word.txt文件
        File file = new File("word.txt");

        // 使用exists()方法检查文件是否存在
        if (file.exists()) {
            // 如果文件存在
            file.delete(); // 调用delete()方法删除该文件
            System.out.println("该文件已经删除"); // 输出提示信息
        } else {
            // 如果文件不存在
            try {
                // 使用createNewFile()方法尝试创建文件
                file.createNewFile();

                System.out.println("该文件已经创建"); // 输出提示信息
            } catch (Exception e) {
                // 捕捉并处理可能发生的异常
                // createNewFile()方法通常不会抛出异常,除非发生了I/O错误
                e.printStackTrace(); // 打印异常堆栈信息
            }
        }
    }
}
2.2 程序运行结果

3、获取文件信息

File类提供了很多方法以获取文件本身信息,其中常用方法如下表:

File类的常用方法
方法 返回值 说明
getName() String 获取文件的名称
canRead() boolean 判断文件是否为可读的
canWrite() boolean 判断文件是否可被写入
exits() boolean 判断文件是否存在
length() long 获取文件的长度(以字节为单位)
getAbsoluterPath() String 获取文件的绝对路径
getParent() String 获取文件的父路径
isFile() boolean 判断文件是否存在
isDirectory() boolean 判断文件是否为一个目录
isHidden() boolean 判断文件是否为隐藏文件
lastModified() long 获取文件最后修改时间
3.1 程序代码(列子)
import java.io.File;

/**
 */
public class FileTest1 {
    public static void main(String[] args){
        File file=new File("word.txt");//创建文件对象
        if(file.exists()){//如果文件存在
            String name=file.getName();//获取文件名称
            long length= file.length();//获取文件长度
            boolean hidden= file.isHidden();//判断文件是否为隐藏文件,是返回true,否返回false
            System.out.println("文件名称:"+name);
            System.out.println("文件长度:"+length);
            System.out.println("该文件是否为隐藏文件:"+hidden);
        }
        else{
            System.out.println("该文件不存在");
        }
    }
}
3.2 程序运行结果