如何定位目录和删除文件?

How to target directories and delete files?

我已经在大学里学习 Java脚本 4 周了,并且我在 2 周前开始学习 Java。事实证明它很有用,因为我们有一个项目,我们必须制作一个程序(无论如何,这就是我们为项目选择的)。

问题是,虽然我了解 Java 的大部分基础知识,但我对制作我们想要制作的程序的了解还不够,而且我的所有其他团队成员甚至从未接触过 Java,有些人甚至在 class.

中使用 JavaScript 挣扎

对不起,顺便说一句,我只是想确保人们了解我的出发点。

无论如何,我们决定制作一个类似于Windows控制面板中的磁盘清理功能的程序。如同,它会删除临时文件和不必要的文件以释放 space。

而且我什至不知道如何开始编写类似的代码。我不要求任何人为我完成整个编码,但我需要快速学习如何制作一个以列出的目录为目标的程序,然后从该目录中删除特定或所有文件。因此,例如,我首先需要它定位的是 Windows 文件夹中的 "Temp" 文件夹,然后删除其中的所有文件和任何子文件夹。

我该怎么做?

此外,这是我第一次在 Stack Overflow 上发帖提问,我真的被左右问的非常复杂的事情弄得不知所措,我一直没有问这个问题,因为我觉得如果我问一些非常简单的问题,并且不在我的问题中放入一大堆复杂的代码,我就会被终止或发生其他事情。

获取临时目录,可以参考这个post,说明是这样的:

System.getProperty("java.io.tmpdir")

此外,关于如何处理文件操作,我建议您阅读 java 找到的文档 here

例如link表示删除一个文件,你可能对方法感兴趣:

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

我还建议您四处搜索并查找一些示例,以及阅读在线 Javadoc 的相关部分。

此外,根据我的经验,如果您不知道自己在做什么,删除文件可能会有点混乱。在尝试之前,您可能需要真正确定自己知道自己在做什么。