Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-6 of 6 total  RSS 

Create ZIP files on the fly

// description of your code here

    def createZIP(self, startdate, enddate):
        """ Create the XTG file and the photos in a ZIP file """
        from StringIO import StringIO
        xtgString = StringIO()
        photofiles = []
        zorionagurrak = self.getZorionAgurrak(startdate, enddate)

        xtgString.write('<v6.50><e0>\r')
        for zorionagurra in zorionagurrak:
            a = self.createZorionAgurraXTG(zorionagurra).getvalue()
            xtgString.write(a)
            photofiles.append((zorionagurra['id'], zorionagurra['photo']))
            
        zipfile = self.appendFiles(xtgString, photofiles)

        request = self.request

        request.response.setHeader('Content-Type', 'application/zip')
        request.response.setHeader('Content-Disposition', 'attachment; filename=zorionagurrak.zip')
        request.response.write(zipfile.getvalue())
        return request.response

Adding files to an existing jar file

Adds files to an existing Zip file.

Overwrites zip entries with the same name as one of the new files.

The function renames the existing zip file to a temporary file and then adds all entries in the existing zip along with the new files, excluding the zip entries that have the same name as one of the new files.


Note: I'm not sure I used the best way to get a temp file. A snippet for that is welcome :)

	
	public static void addFilesToExistingZip(File zipFile,
			 File[] files) throws IOException {
                // get a temp file
		File tempFile = File.createTempFile(zipFile.getName(), null);
                // delete it, otherwise you cannot rename your existing zip to it.
		tempFile.delete();

		boolean renameOk=zipFile.renameTo(tempFile);
		if (!renameOk)
		{
			throw new RuntimeException("could not rename the file "+zipFile.getAbsolutePath()+" to "+tempFile.getAbsolutePath());
		}
		byte[] buf = new byte[1024];
		
		ZipInputStream zin = new ZipInputStream(new FileInputStream(tempFile));
		ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));
		
		ZipEntry entry = zin.getNextEntry();
		while (entry != null) {
			String name = entry.getName();
			boolean notInFiles = true;
			for (File f : files) {
				if (f.getName().equals(name)) {
					notInFiles = false;
					break;
				}
			}
			if (notInFiles) {
				// Add ZIP entry to output stream.
				out.putNextEntry(new ZipEntry(name));
				// Transfer bytes from the ZIP file to the output file
				int len;
				while ((len = zin.read(buf)) > 0) {
					out.write(buf, 0, len);
				}
			}
			entry = zin.getNextEntry();
		}
		// Close the streams		
		zin.close();
		// Compress the files
		for (int i = 0; i < files.length; i++) {
			InputStream in = new FileInputStream(files[i]);
			// Add ZIP entry to output stream.
			out.putNextEntry(new ZipEntry(files[i].getName()));
			// Transfer bytes from the file to the ZIP file
			int len;
			while ((len = in.read(buf)) > 0) {
				out.write(buf, 0, len);
			}
			// Complete the entry
			out.closeEntry();
			in.close();
		}
		// Complete the ZIP file
		out.close();
		tempFile.delete();
	}

unix, pack folder and contents with tar gz

tar -zcvf packagename.tar.gz folder/

Create a single JPG gallery from an image archive

The following comes from Jason Scott and is posted here with permission under the Creative Commons Attribution-ShareAlike License.

The script expands a zip or rar archive of images, makes thumbnails, and compiles the thumbnails into a single JPG to represent what's in the archive. Requires ImageMagick.

Code:
#!/bin/sh
# GALLERATE: Turn a zip of images into a gallery.
# From Jason Scott. http://ascii.textfiles.com/archives/000137.html
if [ -f "$1" ]
   then
   rm -rf .galleryworld
   echo "[%] Preparting to squat out $1...."
   mkdir .galleryworld
   cd .galleryworld
   unzip -j "../$1"
   unrar e -ep "../$1"
   echo "[%] WHY DOES IT HURT!!!!"
   montage +frame +shadow +label -tile 7 *.JPG *.GIF *.gif *.jpg *.bmp *.png *.PNG *.BMP "../$1.jpg"
   cd ..
   rm -rf .galleryworld
   ls -l "$1.jpg"
  else
  echo "No such file, assmaster."
fi


Usage:
GALLERATE [file]

where [file] is the zip or rar archive of images to be processed.

Reading from a zip file

import zipfile

z = zipfile.ZipFile("zipfile.zip", "r")
for filename in z.namelist():
        print filename
        bytes = z.read(filename)
        print len(bytes)

Zip two Arrays together into a Hash

Found this here:

http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/122906
 
def Hash.from_pairs_e(keys,values)
  hash = {}
  keys.size.times { |i| hash[ keys[i] ] = values[i] }
  hash
end 
« Newer Snippets
Older Snippets »
Showing 1-6 of 6 total  RSS