2012-10-05 85 views
53

我正在使用groovy创建一个文件,如"../A/B/file.txt"。为此,我创建了一个service并通过file path创建为argument。该服务然后由Job使用。 Job将执行在指定目录中创建文件的逻辑。我已经手动创建了“A”目录。如何检查包含文件的目录是否存在?

如何通过代码自动创建“A”目录下的“B”目录和file.txt文件?

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

回答

101

要检查文件夹存在或没有,你可以简单的使用方法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" 
} 
8

编辑:作为Java8的你最好使用Files类:

Path resultingPath = Files.createDirectories('A/B'); 

我不知道,如果这最终解决您的问题,但类File有方法mkdirs()充分创建由文件指定的路径。

File f = new File("/A/B/"); 
f.mkdirs(); 
+1

感谢。但是,如何在创建目录的同时创建file.txt? – chemilleX3

+0

是这个f.mkdrs()不是f.mkdir()?谢谢.. – chemilleX3

+0

我现在明白了,它应该是f.mkdrs(),因为我创建了多个目录。谢谢。 – chemilleX3

相关问题