如何检查包含文件的目录是否存在?

che*_*eX3 60 groovy

groovy用来创建一个像这样的文件"../A/B/file.txt".为此,我创建了一个service并将file path其创建为argument.然后,a使用此服务Job.该Job会做逻辑创建在指定的目录中的文件.我手动创建了"A"目录.

如何通过代码在"A"目录中创建"B"目录和file.txt以自动创建它?

我还需要在创建文件之前检查目录"B"和"A"是否存在.

tim*_*tes 113

要检查文件夹是否存在,您只需使用以下exists()方法:

// Create a File object representing the folder 'A/B'
def folder = new File( 'A/B' )

// If it doesn't exist
if( !folder.exists() ) {
  // Create all folders up-to and including B
  folder.mkdirs()
}

// Then, write to file.txt inside B
new File( folder, 'file.txt' ).withWriterAppend { w ->
  w << "Some text\n"
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,这很容易受到竞争条件的影响,因为另一个进程可以在 `.exists()` 和 `.mkdirs()` 调用之间创建目录。我不知道如何在 Groovy 中做到这一点,但通常正确的方法是创建目录并忽略错误(如果它们已经存在)。 (3认同)

Jac*_*ack 8

编辑:从Java8开始,你最好使用Files类:

Path resultingPath = Files.createDirectories('A/B');
Run Code Online (Sandbox Code Playgroud)

我不知道这是否最终解决了你的问题,但类Filemkdirs()完全创建文件指定的路径的方法.

File f = new File("/A/B/");
f.mkdirs();
Run Code Online (Sandbox Code Playgroud)