MATLAB Answers


How do I zip multiple directories and preserve structure

Asked by Michael
on 13 Sep 2013
Latest activity Commented on by per isakson
on 1 Oct 2016 at 22:25

Let's say I have 3 directories, each with their own contents (files and subdirectories).

C:\foo1\ D:\foo2\ E:\foo3\

I want to zip these up so that the zip file contains the following directory structure: \foo1\ \foo2\ \foo3\

So far, I've figured this out: zip(,{foo1_path,foo2_path,foo3_path});

However, this will put all the contents of each of the directories into the zip file - it does not preserve the directory structure of having the actual 'foo1' folder listed in the zip file.

This is a weird one, but due to various permissions issues and other IT issues, this is the only way I can automate my zip file logging...


You cannot invoke an external zip program?

on 16 Sep 2013

Nope, no external programs are available, and new programs cannot be installed.


1 Answer

Answer by Jan Simon
on 15 Sep 2013
Edited by per isakson
on 1 Oct 2016 at 21:05
 Accepted answer

You can call the Java methods as in the zip() command. Some of the methods are not documented and might not work with future Matlab versions, but I have success with this from Matlab 6.5 to R2011b:

fileOut = FileOutputStream('');
zipOut  = ZipOutputStream(fileOut);
% This InterruptibleStreamCopier is unsupported and may change without notice.
StreamCopier = ...;
% You will need a loop over your filres from here...
fileIn = FileInputStream('C:\foo1\File1.txt');
zipObj = ZipEntry('foo1\File1.txt');         % <== relative path name
StreamCopier.copyStream(fileIn, zipOut);
% here
% Close streams:


on 16 Sep 2013

I implemented this in my code. It was kind of uglier than I would have liked, but it does work. I'm on R2012a -thanks!

per isakson
on 1 Oct 2016 at 22:25

It works on R2016a.

Join the 15-year community celebration.

Play games and win prizes!

Learn more
Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!