Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.gdev;
- import java.io.*;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.zip.ZipEntry;
- import java.util.zip.ZipOutputStream;
- /**
- * Created by Андрей on 27.03.2015.
- */
- public class ZipWorker implements IFileWorker {
- TaskQueue queue;
- public ZipWorker(TaskQueue tq)
- {
- queue = tq;
- }
- private long doneData = 0;
- @Override
- public long getProgress() {
- return doneData;
- }
- private void iterateAllFiles(File path) {
- try {
- FileOutputStream fos = new FileOutputStream(path.getAbsolutePath() + "/" + path.getName() + ".zip");
- ZipOutputStream zos = new ZipOutputStream(fos);
- for (File f : path.listFiles()) {
- if (f.isDirectory()) {
- System.out.println("Pushing directory '" + f.getName() + "' as a task...");
- queue.pushTask(f);
- }
- else if (f.getName() != path.getName() + ".zip")
- addToZip(path, f, zos);
- }
- zos.close();
- fos.close();
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- @Override
- public void work(File f) {
- if (f.isDirectory()) {
- iterateAllFiles(f);
- }
- }
- private void writeZipFile(File directoryToZip, List<File> fileList) {
- try {
- FileOutputStream fos = new FileOutputStream(directoryToZip.getName() + ".zip");
- ZipOutputStream zos = new ZipOutputStream(fos);
- for (File file : fileList) {
- if (!file.isDirectory()) { // we only zip files, not directories
- addToZip(directoryToZip, file, zos);
- doneData += file.length();
- }
- }
- zos.close();
- fos.close();
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- private void addToZip(File directoryToZip, File file, ZipOutputStream zos) throws FileNotFoundException,
- IOException {
- FileInputStream fis = new FileInputStream(file);
- // we want the zipEntry's path to be a relative path that is relative
- // to the directory being zipped, so chop off the rest of the path
- String zipFilePath = file.getCanonicalPath().substring(directoryToZip.getCanonicalPath().length() + 1,
- file.getCanonicalPath().length());
- //System.out.println("Writing '" + zipFilePath + "' to zip file");
- ZipEntry zipEntry = new ZipEntry(zipFilePath);
- zos.putNextEntry(zipEntry);
- byte[] bytes = new byte[1024];
- int length;
- while ((length = fis.read(bytes)) >= 0) {
- zos.write(bytes, 0, length);
- doneData += length;
- }
- zos.closeEntry();
- fis.close();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement