Code:
package org.fb.util.backup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* File -> BackupUtility.java
* <p>
* Package -> org.fb.util.backup
* <p>
* Created for -> Nardah - BackupUtility
*
* @author Ethan Kyle Millard
* @since 2/6/2017 @7:42 AM
*/
public class BackupUtility {
private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
public static void main(String...args){
logger.info("Starting up backup utility executor.");
scheduler .scheduleAtFixedRate(()->{ packZip(); }, 12, 12, TimeUnit.HOURS);
}
/**
* The format of the date used in the zip of the folder.
*/
private static final String DATE = DateTimeFormatter.ofPattern("dd-MM-yyyy").format(LocalDate.now());
/**
* The directory of the source or folder to be zipped.
*/
private static final String SOURCE_DIRECTORY_PATH = Paths.get("").toAbsolutePath().toString() + File.separator + "src";
/**
* The destination for the output in zip format.
*/
private static final String DESTINATION_FOR_OUTPUT = Paths.get("").toAbsolutePath().toString() + File.separator + "data" + File.separator + "backup" + File.separator + "src-"+ DATE +".zip";
/**
* A logger to log the output.
*/
private static final Logger logger = LoggerFactory.getLogger(BackupUtility.class);
/**
* Method used to pack all the files from {@code SOURCE_DIRECTORY_PATH} sourceDirPath to the {@code DESTINATION_FOR_OUTPUT}.
*/
public static void packZip() {
try {
/*
* Checks if the File in {@code DESTINATION_FOR_OUTPUT} was already created, if so stop the method.
*/
if (new File(DESTINATION_FOR_OUTPUT).exists()) {
logger.info("The backup has already been created for today.");
return;
}
/*
* Creates a new file.
*/
Path p = Files.createFile(Paths.get(DESTINATION_FOR_OUTPUT));
try (ZipOutputStream zs = new ZipOutputStream(Files.newOutputStream(p))) {
/*
* Converts the {@link String} sourceDirPath to a path.
*/
Path pp = Paths.get(SOURCE_DIRECTORY_PATH);
/*
* Returns a {@link Stream} that will be populated with all the file from given starting point.
*/
Files.walk(pp).filter(path -> !Files.isDirectory(path)).forEach(path -> {
/*
* Constructs a new {@link Zip Entry}.
*/
ZipEntry zipEntry = new ZipEntry(pp.relativize(path).toString());
try {
zs.putNextEntry(zipEntry);
zs.write(Files.readAllBytes(path));
zs.closeEntry();
} catch (Exception e) {
System.err.println(e);
}
});
logger.info("The backup has just been created for the date " + DATE + ".");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Just a small addition, maybe saved a few seconds to someone
Nice