删除文件

前端之家收集整理的这篇文章主要介绍了删除文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

下面是编程之家 jb51.cc 通过网络收集整理的代码片段。

编程之家小编现在分享给大家,也给大家做个参考。

//----------------------------------------------------------------------------------
println new File('/doesnotexist').exists()  // => false
println new File('/doesnotexist').delete()  // => false

new File('/createme') << 'Hi there'
println new File('/createme').exists()  // => true
println new File('/createme').delete()  // => true

names = ['file1','file2','file3']
files = names.collect{ new File(it) }
// create 2 of the files
files[0..1].each{ f -> f << f.name }

def deleteFiles(files) {
    def problemFileNames = []
    files.each{ f ->
        if (!f.delete())
            problemFileNames += f.name
    }
    def delCnt = files.size() - problemFileNames.size()
    println "Successfully deleted $delCnt of ${files.size()} file(s)"
    if (problemFileNames)
        println "Problems file(s): " + problemFileNames.join(',')
}

deleteFiles(files)
// =>
// Successfully deleted 2 of 3 file(s)
// Problems file(s): file3

// we can also set files for deletion on exit
tempFile = new File('/xxx')
assert !tempFile.exists()
tempFile << 'junk'
assert tempFile.exists()
tempFile.deleteOnExit()
assert tempFile.exists()
// To confirm this is working,run these steps multiple times in a row.

// Discussion:
// Be careful with deleteOnExit() as there is no way to cancel it.
// There are also mechanisms specifically for creating unqiuely named temp files.
// On completion of JSR 203,there will be additional methods available for
// deleting which throw exceptions with detailed error messages rather than
// just return booleans.
//----------------------------------------------------------------------------------

以上是编程之家(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。

如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。

猜你在找的Groovy相关文章