1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- import java.nio.*
- import java.nio.file.*
- /**
- * This will completely re-write a file, be careful.
- *
- * Simple Usage:
- *
- * modifyFile("C:\whatever\whatever.txt") {
- * if(it.contains("soil"))
- * return null // remove dirty word
- * else
- * return it
- * }
- *
- * The closure must return the line passed in to keep it in the file or alter it, any alteration
- * will be written in its place.
- *
- * To delete an entire line instead of changing it, return null
- * To add more lines after a given line return: it + "\n" + moreLines
- *
- * Notice that you add "\n" before your additional lines and not after the last
- * one because this method will normally add one for you.
- */
- def modifyFile(srcFile, Closure c) {
- modifyFile(srcFile, srcFile, c)
- }
- def modifyFile(srcFile, destFile, Closure c={println it;return it}) {
- StringBuffer ret = new StringBuffer();
- File src = new File(srcFile)
- File dest = new File(destFile)
- src.withReader{reader->
- reader.eachLine{
- def line=c(it)
- if(line != null) {
- ret.append(line)
- ret.append("\n")
- }
- }
- }
- dest.delete()
- dest.write(ret.toString())
- }
- /**
- * Copies a file specified at 'origin' to 'destination'.
- * If 'overwrite' is set to true any existing file at 'destination' is overwritten (defaults to false).
- */
- def copyFile(String origin, String destination, boolean overwrite=false){
- Path origPath = Paths.get(origin)
- Path destPath = Paths.get(destination)
- def fileAtDestination = destPath.toFile()
- if(fileAtDestination.exists()){
- if(overwrite) {
- fileAtDestination.delete()
- Files.copy(origPath, destPath)
- }
- else{
- println("Won't overwrite existing file $fileAtDestination")
- println("Call 'copyFile(orig, dest, true)' to delete the existing file first")
- }
- }
- else {
- // There's no file at the destination yet
- Files.copy(origPath, destPath)
- }
- }
- // Define methods visible to other Gradle scripts
- ext{
- modifyFile = this.&modifyFile
- copyFile = this.©File
- }
|