我在同一目录中有两个名称几乎相同的文件,例如“myfile_1234.mp4”和“myfile_5678.mp4”。例如,一个文件“myfile_1234.mp4”的大小为零字节,而另一个文件“myfile_5678.mp4”的大小不等于零(例如 32kb)。现在我想从目录中删除第一个文件,但不删除其他文件。
我们可以有一个类似循环临时指针的东西来指向目录中的文件,然后我们将检查文件的大小并在其大小为零时将其删除。
有人可以帮我吗...?
最佳答案
这是一个相对简单的练习。以下是您需要了解的事情才能了解要做什么:
- 目录由
File
对象表示。为要列出的目录创建一个File
对象 listFiles()
调用会生成目录中所有文件的数组length()
方法返回文件的大小delete()
方法删除文件
您的代码将如下所示:
// Reference the directory in which the files reside
File dir = new File("c:/my/test/directory");
// Go through the files in the directory in a loop
for ( File file : dir.listFiles()) {
// Make sure that an entry is a file (it could be a directory)
// and that its size is zero
if (file.isFile() && file.length() == 0) {
// If both conditions are true, delete the empty file
file.delete();
}
}
您可以设置附加条件来检查文件是否具有特定名称、扩展名等。
关于java - Java删除同名文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20940082/