Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class ZipFileManager {
- private Path zipFile;
- public ZipFileManager(Path zipFile) {
- this.zipFile = zipFile;
- }
- public void createZip(Path source) throws Exception{
- if (!Files.exists(zipFile.getParent())){
- Files.createDirectories(zipFile.getParent());
- }
- try (ZipOutputStream zipOutputStream = new ZipOutputStream(Files.newOutputStream(zipFile))) {
- if (Files.isRegularFile(source)) {
- addNewZipEntry(zipOutputStream, source.getParent(), source.getFileName());
- }
- else if (Files.isDirectory(source)){
- FileManager fileManager = new FileManager(source);
- List<Path> fileNames = fileManager.getFileList();
- for (Path path : fileNames){
- addNewZipEntry(zipOutputStream, path.getParent(), path);
- }
- }
- else {
- throw new PathNotFoundException();
- }
- /*ZipEntry zipEntry = new ZipEntry(source.getFileName().toString());
- zipOutputStream.putNextEntry(zipEntry);
- try (InputStream inputStream = Files.newInputStream(source)) {
- while (inputStream.available() > 0) {
- zipOutputStream.write(inputStream.read());
- }
- }*/
- }
- }
- private void addNewZipEntry(ZipOutputStream zipOutputStream, Path filePath, Path fileName) throws Exception{
- try(InputStream inputStream = Files.newInputStream(filePath.resolve(fileName))) {
- ZipEntry zipEntry = new ZipEntry(fileName.toString());
- zipOutputStream.putNextEntry(zipEntry);
- copyData(inputStream, zipOutputStream);
- /*while (inputStream.available() > 0) {
- zipOutputStream.write(inputStream.read());
- }*/
- zipOutputStream.closeEntry();
- }
- }
- private void copyData(InputStream in, OutputStream out) throws Exception{
- while (in.available() > 0){
- out.write(in.read());
- }
- }
- }
Add Comment
Please, Sign In to add comment