File类、FileInputStream类、FileOutputStream类、FileReader类、BufferedReader类、FileWriter类和BufferedWriter类详解

File类

File 类是 Java 中用于表示文件和目录路径名的类。它的作用主要是通过路径名操作文件和目录,例如创建、删除、重命名等。绝对路径(absolute path)和相对路径(relative path)都是用来指定文件或目录在文件系统中位置的方式。

那么什么是绝对路径,什么是相对路径呢?

绝对路径指的是文件或目录在文件系统中的完整路径,从根目录开始一直到目标文件或目录的路径。在不同的操作系统中表示方式有所不同:

  • 在Unix/Linux系统中,绝对路径从根目录 / 开始,如 /home/user/file.txt

  • 在Windows系统中,绝对路径可能以驱动器名或网络路径开始,如 C:\Users\User\file.txt\\server\share\file.txt

相对路径指的是文件或目录相对于当前工作目录(或另一个已知的基准路径)的路径。它不是完整的路径,而是从一个参考位置出发的路径。相对路径可以是向上或向下的路径,使用相对当前位置的目录层次结构来指定目标文件或目录的位置。例如:

  • ../parent_directory/file.txt 表示向上一级目录,然后进入 parent_directory 目录下的 file.txt 文件。

  • subdirectory/file.txt 表示当前目录下的 subdirectory 目录中的 file.txt 文件。

绝对路径和相对路径的选择取决于需要的准确性和灵活性。绝对路径提供了确切的文件位置,不受当前工作目录的影响,适用于需要确切路径的情况。相对路径则更加灵活,可以根据当前工作环境的变化而适应不同的目录结构,使得项目或脚本更易于移植和管理。

构造方法

File(String pathname)

功能:通过指定路径名创建一个 File 对象。

String filePath = "C:/Users/John/Documents/example.txt";
File file = new File(filePath);

File(String parent, String child)

功能:通过父路径和子路径名创建一个 File 对象。

String parentPath = "C:/Users/John/Documents";
String childPath = "example.txt";
File file = new File(parentPath, childPath);

File(File parent, String child)

功能:通过父 File 对象和子路径名创建一个 File 对象。

File parentDir = new File("C:/Users/John/Documents");
String childPath = "example.txt";
File file = new File(parentDir, childPath);
文件操作方法

boolean createNewFile()

功能:创建一个新文件。

File newFile = new File("C:/Users/John/Documents/newFile.txt");
try {
    boolean created = newFile.createNewFile();
    if (created) {
        System.out.println("文件创建成功");
    } else {
        System.out.println("文件已存在或创建失败");
    }
} catch (IOException e) {
    e.printStackTrace();
}

boolean delete()

功能:删除文件或目录。

File fileToDelete = new File("C:/Users/John/Documents/fileToDelete.txt");
boolean deleted = fileToDelete.delete();
if (deleted) {
    System.out.println("文件删除成功");
} else {
    System.out.println("文件删除失败");
}

boolean renameTo(File dest)

功能:重命名文件或目录。

File oldFile = new File("C:/Users/John/Documents/oldName.txt");
File newFile = new File("C:/Users/John/Documents/newName.txt");
boolean renamed = oldFile.renameTo(newFile);
if (renamed) {
    System.out.println("文件重命名成功");
} else {
    System.out.println("文件重命名
  • 21
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

无知、508

你的鼓励实我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值