我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)
编辑:从Java8开始,你最好使用Files类:
Path resultingPath = Files.createDirectories('A/B');
Run Code Online (Sandbox Code Playgroud)
我不知道这是否最终解决了你的问题,但类File有mkdirs()完全创建文件指定的路径的方法.
File f = new File("/A/B/");
f.mkdirs();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
98736 次 |
| 最近记录: |