Skip to content

Instantly share code, notes, and snippets.

@atlasloewenherz
Last active August 29, 2015 13:55
Show Gist options
  • Save atlasloewenherz/8781566 to your computer and use it in GitHub Desktop.
Save atlasloewenherz/8781566 to your computer and use it in GitHub Desktop.
java.io.File on Steroid, enables you to new File(zipFilePath).unzip(destination) || new File(dirPath).zip(destination) || new File(FilePath).replace()
package utils
import java.util.Map
import java.util.zip.ZipOutputStream
import java.util.zip.ZipInputStream
import java.util.zip.ZipEntry
import groovy.text.SimpleTemplateEngine
class BootStrap {
void boot() {
File.metaClass.zip = { String destination,base ->
def result = new ZipOutputStream(new FileOutputStream(destination))
result.withStream {zipOutStream->
delegate.eachFileRecurse { f ->
if(!f.isDirectory()) {
//base= base.replace('/', File.separator)
def filePath = f.getPath().toString()
filePath = filePath.replace(File.separator, '/')
//println 'base: ' +base
//println filePath
zipOutStream.putNextEntry(new ZipEntry(filePath.replace(base,'')))
new FileInputStream(f).withStream { inStream ->
def buffer = new byte[1024]
def count
while((count = inStream.read(buffer)) > 0) {
zipOutStream.write(buffer,0 ,count)
}
}
zipOutStream.closeEntry()
}
}
}
}
File.metaClass.unzip = { String dest ->
def result = new ZipInputStream(new FileInputStream(delegate))
def destFile = new File(dest)
if(!destFile.exists()){
destFile.mkdir();
}
result.withStream{
def entry
while(entry = result.nextEntry){
if (!entry.isDirectory()){
new File(dest + File.separator + entry.name).parentFile?.mkdirs()
def output = new FileOutputStream(dest + File.separator+ entry.name)
output.withStream{
int len = 0;
byte[] buffer = new byte[4096]
while ((len = result.read(buffer)) > 0){
output.write(buffer, 0, len);
}
}
} else {
new File(dest + File.separator + entry.name).mkdir()
}
}
}
}
File.metaClass.replace = { Map binding, String destination ->
def templateText = delegate.text
def engine = new SimpleTemplateEngine()
def configFileContent = engine.createTemplate(templateText).make(binding)
def configFile = new File(destination)
if (!configFile.exists()){
configFile << configFileContent
}else{
def backupFile = new File(destination+'.backup')
configFile.renameTo(backupFile)
configFile.delete()
def newConfigFile = new File(destination)
newConfigFile << configFileContent
}
}
File.metaClass.copy = { String destination ->
def out = new File(destination).newDataOutputStream()
out << delegate.newDataInputStream()
delegate.newDataInputStream().close()
out.close()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment