文件的删除方法实际上是如何删除的?

How & What does the delete method for a file actually delete?

假设我创建了一个 txt 文件并将其保存为 "Untitled1"。我输入 eclipse 并输入以下内容:

import java.io.*;
public class Test {

public static void main(String[] args){
File f = new File("Untitled1.txt");
boolean isDeleted = f.delete();

System.out.println(isDeleted);

       }
}

delete 方法返回 False,表示文件未被删除。我知道文件对象代表文件的位置而不是文件的内容。但实际上被删除的是什么?如何删除文件的位置,而不删除文件本身的内容?

我还输入了 Untitled1 文件的文件路径作为文件对象构造函数的参数,它也没有删除 Untitled1.txt 文件。

所以,文件本身被删除了。可能出于各种原因返回 False。

public boolean delete()

Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a directory, then the directory must be empty in order to be deleted. Note that the Files class defines the delete method to throw an IOException when a file cannot be deleted. This is useful for error reporting and to diagnose why a file cannot be deleted.

Returns: true if and only if the file or directory is successfully deleted; false otherwise

Throws:

SecurityException - If a security manager exists and its SecurityManager.checkDelete(java.lang.String) method denies delete access to the file

抓住SecurityException,您可能会发现不允许您以编程方式直接删除文件。

文件由其在文件系统中的路径标识,从根节点开始。

路径的表示取决于系统。例如在 windows C:\foo\bar 而在 linux /home/foo/bar.

所以在下面的代码中,字符串路径将被转换为抽象路径名,它会创建 File 实例,当你调用 delete 方法时,它会尝试删除节点。基本上内容和路径没有太大区别。

File f = new File("Untitled1.txt");

首先,请注意 File 是旧的,bad class,现在不应该使用。

使用 Files class 更好,更具体地说是 delete 方法。

至于究竟删除了什么:文件是位于硬盘中的一堆字节。磁盘 - 或其分区之一 - 被格式化为 文件系统 ,这是一种组织目录和文件的数据结构。特定的文件系统规定了文件如何被分解成片段,这些片段如何通过 seekread

文件系统有目录,它们为您提供了文件的起点。目录层次结构中的文件路径告诉系统在哪里可以找到文件,包括它的所有信息(如指向其开始的指针,read/write 权限等)目录中的信息告诉实际文件内容在哪里is 有时被称为 "link"(至少在 Unix 文件系统中)。

当您删除文件时,通常会发生的事情是从该目录中删除该文件的特定 link。如果那是最后一个 link(该文件可以从多个目录 link 编辑,至少在某些文件系统中是这样),属于该文件的块也被标记为空闲,以便它们可以分配到另一个文件。

所以你的 File 对象告诉系统文件在哪里,但是 delete 操作最终告诉系统从目录中取消 link 文件(倒数第二部分路径),如果这是最后一个 link,它还会告诉系统转​​到文件内容并将其标记为可用。

这是一般性描述。确切的细节以及当内容被标记为免费时会发生什么取决于所使用的特定文件系统(例如 ext4、reiserFS... (Linux)、HFS+ (MacOS X)、NTFS、FAT32... (Windows)).