简体   繁体   English

Scala删除所有文件,但不删除目录

[英]scala delete all files but not directory

I have a directory and subfolder in it. 我有一个目录和子文件夹。 The directory contains 5 file and one subdirectory. 该目录包含5个文件和1个子目录。 I need to empty the subfolder and delete 3 files out of 5. 我需要清空子文件夹并从5个文件中删除3个文件。

Currently I am using below code which is deleting the file but sub folder is not getting empty. 目前,我正在使用下面的代码删除文件,但子文件夹不会变空。 Please suggest 请建议

  Files.deleteIfExists(Paths.get("src/main/tempDir/doc-topics-new.txt"))
  Files.deleteIfExists(Paths.get("src/main/tempDir/new_corpus.mallet"))
  Files.deleteIfExists(Paths.get("src/main/tempDir/corpus.mallet"))
  Files.deleteIfExists(Paths.get("src/main/tempDir/sub_directory/*"))

better-files supports deleting all children in directory with file.clear() whilst files could be deleted with file.delete() . better-files支持使用file.clear()删除目录中的所有子项,而文件可以使用file.delete()删除。 Here is a working example 这是一个有效的例子

import better.files._

object Hello extends App {
    val subdirectory = file"/path/to/subdirectory"
    subDirectory.clear()

    val file1 = file"/path/to/file1.txt"
    file1.delete()
}

where we need the following dependency 我们需要以下依赖

libraryDependencies += "com.github.pathikrit" %% "better-files" % "3.8.0"

You can delete the files from the subdirectory (but not the directory itself) like this: 您可以像下面这样从子目录(而不是目录本身)中删除文件:

def deleteOnlyFiles(file: File): Unit = {
  if (file.isDirectory) {
    file.listFiles.foreach(deleteOnlyFiles)
  } else {
     if (file.exists && !file.delete) {
       throw new Exception(s"Unable to delete ${file.getAbsolutePath}")
     }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM