Java/File Input Output/Zip Tar File
Версия от 18:01, 31 мая 2010; (обсуждение)
Содержание
- 1 A single checksum calculation for multiple files
- 2 bzip source code
- 3 Calculating the Checksum of a Byte Array (Compute Adler-32 checksum)
- 4 Calculating the Checksum of a File
- 5 Check sum for an InputStream
- 6 Check sum for a path
- 7 Compare two zip files
- 8 Compress a Byte Array
- 9 Compressing a Byte Array
- 10 Compressing Streams: File Summer
- 11 Compressing Streams: Parity Checksum
- 12 Compressing Streams: Zipper, Java example
- 13 Compress string(byte array) by Deflater
- 14 Compute CRC-32 checksum
- 15 Create a simple ZIP File: not retain any directory path information about the files.
- 16 Create a zip file with java.util.zip package
- 17 Create checksum for a zip file
- 18 Creating a ZIP File
- 19 Decompress a Byte Array
- 20 Decompress a ZIP file.
- 21 Decompress a zip file using ZipFile
- 22 Decompress a zip file using ZipInputStream
- 23 Decompressing a Byte Array
- 24 Determine whether a file is a ZIP File.
- 25 Displaying contents of a compressed zip file
- 26 Extract contents of a zip file
- 27 Extract file/files from a zip file
- 28 Extract zip file to destination folder
- 29 Listing the Contents of a ZIP File
- 30 List the contents of a zip file
- 31 List the entries of a zip file
- 32 Load zip file and scan zip file
- 33 Makes a zip file named xmlFileName from xmlURL at path
- 34 Making a zip file of directory including its subdirectories recursively
- 35 Package files utility
- 36 Provides both writing and reading from a file which is transparently compressed in Zip
- 37 Put file To Zip File
- 38 Read a zip file checksum value
- 39 Read entries in a zip / compressed file
- 40 Read files within a zip file
- 41 Reading the Contents of a ZIP File
- 42 Read the content of a zip file ZipFile
- 43 Read zip file
- 44 Retrieve a compressed file from a ZIP file
- 45 Retrieve the contents of a ZIP file
- 46 Retrieving a Compressed File from a ZIP File
- 47 Return the first directory of this archive. This is needed to determine the plugin directory
- 48 Tape Archive Lister: Tar file
- 49 Tar file and untar file
- 50 Tar file stream
- 51 TarInputStream reads a UNIX tar archive as an InputStream
- 52 TarOutputStream writes a UNIX tar archive as an OutputStream
- 53 The java.util.zip package can be used to create a checksum.
- 54 Unpack an archive from a URL
- 55 Unpack a segment from a zip
- 56 Unpack a zip file
- 57 Unzip file to a directory
- 58 UnZip -- print or unzip a JAR or PKZIP file using java.util.zip
- 59 Unzipps a zip file placed at zipURL to path
- 60 Use Java code to zip a folder
- 61 Uses Zip compression to compress any number of files given on the command line
- 62 Validate that an archive contains a named entry
- 63 Write Zip file
- 64 Zip a list of file into one zip file.
- 65 Zip Compare
- 66 Zip unzip byte array
- 67 Zip up a directory
A single checksum calculation for multiple files
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.zip.Adler32;
import java.util.zip.CheckedInputStream;
import java.util.zip.Checksum;
/**
* Perform a single checksum calculation for multiple files
*
* @author
* @version $Id$
*/
public class MultiFileChecksumHelper
{
public static long getChecksum(File[] files)
{
CheckedInputStream cis = null;
FileInputStream is = null;
Checksum checksum = new Adler32();
byte[] tempBuf = new byte[128];
for ( int i = 0; i < files.length && files[i] != null && files[i].exists() && files[i].isFile(); i++ )
{
try
{
is = new FileInputStream(files[i]);
cis = new CheckedInputStream(is, checksum);
while (cis.read(tempBuf) >= 0) {}
}
catch (Exception e)
{
throw new RuntimeException(e);
}
finally
{
if (cis != null)
{
try
{
cis.close();
}
catch (IOException ioe) {}
cis = null;
}
if (is != null)
{
try
{
is.close();
}
catch (IOException ioe) {}
is = null;
}
}
}
return checksum.getValue();
}
}
bzip source code
Calculating the Checksum of a Byte Array (Compute Adler-32 checksum)
import java.util.zip.Adler32;
import java.util.zip.Checksum;
public class Main {
public static void main(String[] argv) throws Exception {
byte[] bytes = "some data".getBytes();
Checksum checksumEngine = new Adler32();
checksumEngine.update(bytes, 0, bytes.length);
long checksum = checksumEngine.getValue();
}
}
Calculating the Checksum of a File
import java.io.FileInputStream;
import java.util.zip.Adler32;
import java.util.zip.CheckedInputStream;
public class Main {
public static void main(String[] argv) throws Exception {
CheckedInputStream cis = new CheckedInputStream(new FileInputStream("filename"), new Adler32());
byte[] tempBuf = new byte[128];
while (cis.read(tempBuf) >= 0) {
}
long checksum = cis.getChecksum().getValue();
}
}
Check sum for an InputStream
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.Adler32;
import java.util.zip.CheckedInputStream;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* implements checksum related utilities
*
* @author
* @version $Id: ChecksumHelper.java 516448 2007-03-09 16:25:47Z ate $
*/
final class ChecksumHelper
{
public static long getChecksum(InputStream is)
{
CheckedInputStream cis = null;
long checksum = 0;
try
{
cis = new CheckedInputStream(is, new Adler32());
byte[] tempBuf = new byte[128];
while (cis.read(tempBuf) >= 0)
{
}
checksum = cis.getChecksum().getValue();
}
catch (IOException e)
{
checksum = 0;
}
finally
{
if (cis != null)
{
try
{
cis.close();
}
catch (IOException ioe)
{
}
}
}
return checksum;
}
}
Check sum for a path
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.Adler32;
import java.util.zip.CheckedInputStream;
/**
* implements common directory and jar operations
*
* @author
* @version $Id: ChecksumHelper.java 516448 2007-03-09 16:25:47Z ate $
*/
final class ChecksumHelper
{
public static long getChecksum(InputStream is)
{
CheckedInputStream cis = null;
long checksum = 0;
try
{
cis = new CheckedInputStream(is, new Adler32());
byte[] tempBuf = new byte[128];
while (cis.read(tempBuf) >= 0)
{
}
checksum = cis.getChecksum().getValue();
}
catch (IOException e)
{
checksum = 0;
}
finally
{
if (cis != null)
{
try
{
cis.close();
}
catch (IOException ioe)
{
}
}
}
return checksum;
}
}
Compare two zip files
/* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
// From xml beans
public class ZipCompare {
public static void main(String[] args) {
if (args.length != 2) {
System.out.println("Usage: zipcompare [file1] [file2]");
System.exit(1);
}
ZipFile file1;
try {
file1 = new ZipFile(args[0]);
} catch (IOException e) {
System.out.println("Could not open zip file " + args[0] + ": " + e);
System.exit(1);
return;
}
ZipFile file2;
try {
file2 = new ZipFile(args[1]);
} catch (IOException e) {
System.out.println("Could not open zip file " + args[0] + ": " + e);
System.exit(1);
return;
}
System.out.println("Comparing " + args[0] + " with " + args[1] + ":");
Set set1 = new LinkedHashSet();
for (Enumeration e = file1.entries(); e.hasMoreElements();)
set1.add(((ZipEntry) e.nextElement()).getName());
Set set2 = new LinkedHashSet();
for (Enumeration e = file2.entries(); e.hasMoreElements();)
set2.add(((ZipEntry) e.nextElement()).getName());
int errcount = 0;
int filecount = 0;
for (Iterator i = set1.iterator(); i.hasNext();) {
String name = (String) i.next();
if (!set2.contains(name)) {
System.out.println(name + " not found in " + args[1]);
errcount += 1;
continue;
}
try {
set2.remove(name);
if (!streamsEqual(file1.getInputStream(file1.getEntry(name)), file2.getInputStream(file2
.getEntry(name)))) {
System.out.println(name + " does not match");
errcount += 1;
continue;
}
} catch (Exception e) {
System.out.println(name + ": IO Error " + e);
e.printStackTrace();
errcount += 1;
continue;
}
filecount += 1;
}
for (Iterator i = set2.iterator(); i.hasNext();) {
String name = (String) i.next();
System.out.println(name + " not found in " + args[0]);
errcount += 1;
}
System.out.println(filecount + " entries matched");
if (errcount > 0) {
System.out.println(errcount + " entries did not match");
System.exit(1);
}
System.exit(0);
}
static boolean streamsEqual(InputStream stream1, InputStream stream2) throws IOException {
byte[] buf1 = new byte[4096];
byte[] buf2 = new byte[4096];
boolean done1 = false;
boolean done2 = false;
try {
while (!done1) {
int off1 = 0;
int off2 = 0;
while (off1 < buf1.length) {
int count = stream1.read(buf1, off1, buf1.length - off1);
if (count < 0) {
done1 = true;
break;
}
off1 += count;
}
while (off2 < buf2.length) {
int count = stream2.read(buf2, off2, buf2.length - off2);
if (count < 0) {
done2 = true;
break;
}
off2 += count;
}
if (off1 != off2 || done1 != done2)
return false;
for (int i = 0; i < off1; i++) {
if (buf1[i] != buf2[i])
return false;
}
}
return true;
} finally {
stream1.close();
stream2.close();
}
}
}
Compress a Byte Array
import java.io.ByteArrayOutputStream;
import java.util.zip.Deflater;
public class Main {
public static void main(String[] argv) throws Exception {
byte[] input = "asdf".getBytes();
Deflater compressor = new Deflater();
compressor.setLevel(Deflater.BEST_COMPRESSION);
compressor.setInput(input);
compressor.finish();
ByteArrayOutputStream bos = new ByteArrayOutputStream(input.length);
byte[] buf = new byte[1024];
while (!compressor.finished()) {
int count = compressor.deflate(buf);
bos.write(buf, 0, count);
}
bos.close();
byte[] compressedData = bos.toByteArray();
}
}
Compressing a Byte Array
import java.io.ByteArrayOutputStream;
import java.util.zip.Deflater;
public class Main {
public static void main(String[] argv) throws Exception {
byte[] input = "this is a test".getBytes();
Deflater compressor = new Deflater();
compressor.setLevel(Deflater.BEST_COMPRESSION);
compressor.setInput(input);
compressor.finish();
ByteArrayOutputStream bos = new ByteArrayOutputStream(input.length);
byte[] buf = new byte[1024];
while (!compressor.finished()) {
int count = compressor.deflate(buf);
bos.write(buf, 0, count);
}
bos.close();
byte[] compressedData = bos.toByteArray();
}
}
Compressing Streams: File Summer
import java.io.FileInputStream;
import java.io.IOException;
import java.util.zip.CRC32;
import java.util.zip.Checksum;
public class Main {
public static void main(String[] args) throws IOException {
FileInputStream fin = new FileInputStream("a.zip");
Checksum cs = new CRC32();
for (int b = fin.read(); b != -1; b = fin.read()) {
cs.update(b);
}
System.out.println(cs.getValue());
fin.close();
}
}
Compressing Streams: Parity Checksum
import java.util.zip.Checksum;
public class ParityChecksum implements Checksum {
long checksum = 0;
public void update(int b) {
int numOneBits = 0;
for (int i = 1; i < 256; i *= 2) {
if ((b & i) != 0)
numOneBits++;
}
checksum = (checksum + numOneBits) % 2;
}
public void update(byte data[], int offset, int length) {
for (int i = offset; i < offset + length; i++) {
this.update(data[i]);
}
}
public long getValue() {
return checksum;
}
public void reset() {
checksum = 0;
}
}
Compressing Streams: Zipper, Java example
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class Main {
public static void main(String[] args) throws IOException {
String outputFile = "a.zip";
int level = 9;
FileOutputStream fout = new FileOutputStream(outputFile);
ZipOutputStream zout = new ZipOutputStream(fout);
zout.setLevel(level);
ZipEntry ze = new ZipEntry("a.zip");
FileInputStream fin = new FileInputStream("b.dat");
zout.putNextEntry(ze);
for (int c = fin.read(); c != -1; c = fin.read()) {
zout.write(c);
}
fin.close();
zout.close();
}
}
Compress string(byte array) by Deflater
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.Deflater;
public class Main {
public static void main(String[] args) throws IOException {
Deflater def = new Deflater();
byte[] input = new byte[1024];
byte[] output = new byte[1024];
FileInputStream fin = new FileInputStream("a.dat");
FileOutputStream fout = new FileOutputStream("b.dat");
int numRead = fin.read(input);
def.setInput(input, 0, numRead);
while (!def.needsInput()) {
int numCompressedBytes = def.deflate(output, 0, output.length);
if (numCompressedBytes > 0) {
fout.write(output, 0, numCompressedBytes);
}
}
def.finish();
fin.close();
fout.flush();
fout.close();
def.reset();
}
}
Compute CRC-32 checksum
import java.util.zip.CRC32;
import java.util.zip.Checksum;
public class Main {
public static void main(String[] argv) throws Exception {
byte[] bytes = "some data".getBytes();
// Compute Adler-32 checksum
Checksum checksumEngine = new CRC32();
checksumEngine.update(bytes, 0, bytes.length);
long checksum = checksumEngine.getValue();
checksumEngine.reset();
}
}
Create a simple ZIP File: not retain any directory path information about the files.
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class Main {
static String rmPath(String fName) {
int pos = fName.lastIndexOf(File.separatorChar);
if (pos > -1)
fName = fName.substring(pos + 1);
return fName;
}
public static void main(String args[]) throws Exception {
ZipOutputStream fout = new ZipOutputStream(new BufferedOutputStream(
new FileOutputStream(args[0])));
for (int n = 1; n < args.length; n++) {
BufferedInputStream fin = new BufferedInputStream(new FileInputStream(
args[n]));
ZipEntry ze = new ZipEntry(rmPath(args[n]));
fout.putNextEntry(ze);
int i;
do {
i = fin.read();
if (i != -1)
fout.write(i);
} while (i != -1);
fout.closeEntry();
fin.close();
System.out.println("Compressing " + args[n]);
System.out.println(" Original Size: " + ze.getSize()
+ " Compressed Size: " + ze.getCompressedSize() + "\n");
}
fout.close();
}
}
Create a zip file with java.util.zip package
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
class makeZipFile {
public static void main(String[] args) throws Exception {
makeZipFile list = new makeZipFile();
list.doZip("a.txt", "a.zip");
}
public void doZip(String filename, String zipfilename) throws Exception {
byte[] buf = new byte[1024];
FileInputStream fis = new FileInputStream(filename);
fis.read(buf, 0, buf.length);
CRC32 crc = new CRC32();
ZipOutputStream s = new ZipOutputStream((OutputStream) new FileOutputStream(zipfilename));
s.setLevel(6);
ZipEntry entry = new ZipEntry(filename);
entry.setSize((long) buf.length);
crc.reset();
crc.update(buf);
entry.setCrc(crc.getValue());
s.putNextEntry(entry);
s.write(buf, 0, buf.length);
s.finish();
s.close();
}
}
Create checksum for a zip file
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class Main {
public static void main(String[] args) throws Exception {
CheckedOutputStream checksum = new CheckedOutputStream(
new FileOutputStream("data.zip"), new Adler32());
ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(checksum));
int size = 0;
byte[] buffer = new byte[1024];
File dir = new File(".");
String[] files = dir.list();
for (int i = 0; i < files.length; i++) {
System.out.println("Compressing: " + files[i]);
FileInputStream fis = new FileInputStream(files[i]);
ZipEntry zipEntry = new ZipEntry(files[i]);
zos.putNextEntry(zipEntry);
while ((size = fis.read(buffer, 0, buffer.length)) > 0) {
zos.write(buffer, 0, size);
}
zos.closeEntry();
fis.close();
}
zos.close();
System.out.println("Checksum : " + checksum.getChecksum().getValue());
}
}
Creating a ZIP File
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class Main {
public static void main(String[] argv) throws Exception {
String[] filenames = new String[] { "filename1", "filename2" };
byte[] buf = new byte[1024];
String outFilename = "outfile.zip";
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outFilename));
for (int i = 0; i < filenames.length; i++) {
FileInputStream in = new FileInputStream(filenames[i]);
out.putNextEntry(new ZipEntry(filenames[i]));
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.closeEntry();
in.close();
}
out.close();
}
}
Decompress a Byte Array
import java.io.ByteArrayOutputStream;
import java.util.zip.Inflater;
public class Main {
public static void main(String[] argv) throws Exception {
byte[] compressedData = null;
Inflater decompressor = new Inflater();
decompressor.setInput(compressedData);
ByteArrayOutputStream bos = new ByteArrayOutputStream(compressedData.length);
byte[] buf = new byte[1024];
while (!decompressor.finished()) {
int count = decompressor.inflate(buf);
bos.write(buf, 0, count);
}
bos.close();
byte[] decompressedData = bos.toByteArray();
}
}
Decompress a ZIP file.
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class Main {
public static void main(String[] argv) throws Exception {
ZipFile zf = new ZipFile("a.zip");
Enumeration<? extends ZipEntry> files = zf.entries();
while (files.hasMoreElements()) {
ZipEntry ze = files.nextElement();
System.out.println("Decompressing " + ze.getName());
System.out.println(" Compressed Size: " + ze.getCompressedSize()
+ " Expanded Size: " + ze.getSize() + "\n");
BufferedInputStream fin = new BufferedInputStream(zf.getInputStream(ze));
BufferedOutputStream fout = new BufferedOutputStream(
new FileOutputStream(ze.getName()));
int i;
do {
i = fin.read();
if (i != -1)
fout.write(i);
} while (i != -1);
fout.close();
fin.close();
}
zf.close();
}
}
Decompress a zip file using ZipFile
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class Main {
public static void main(String[] args) throws Exception {
String zipname = "data.zip";
ZipFile zipFile = new ZipFile(zipname);
Enumeration enumeration = zipFile.entries();
while (enumeration.hasMoreElements()) {
ZipEntry zipEntry = (ZipEntry) enumeration.nextElement();
System.out.println("Unzipping: " + zipEntry.getName());
BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(zipEntry));
int size;
byte[] buffer = new byte[2048];
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(zipEntry.getName()), buffer.length);
while ((size = bis.read(buffer, 0, buffer.length)) != -1) {
bos.write(buffer, 0, size);
}
bos.flush();
bos.close();
bis.close();
}
}
}
Decompress a zip file using ZipInputStream
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class Main {
public static void main(String[] args) throws Exception {
String zipname = "data.zip";
FileInputStream fis = new FileInputStream(zipname);
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
System.out.println("Unzipping: " + entry.getName());
int size;
byte[] buffer = new byte[2048];
FileOutputStream fos = new FileOutputStream(entry.getName());
BufferedOutputStream bos = new BufferedOutputStream(fos, buffer.length);
while ((size = zis.read(buffer, 0, buffer.length)) != -1) {
bos.write(buffer, 0, size);
}
bos.flush();
bos.close();
}
zis.close();
fis.close();
}
}
Decompressing a Byte Array
import java.io.ByteArrayOutputStream;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
public class Main {
public static void main(String[] argv) throws Exception {
byte[] input = "this is a test".getBytes();
Deflater compressor = new Deflater();
compressor.setLevel(Deflater.BEST_COMPRESSION);
compressor.setInput(input);
compressor.finish();
ByteArrayOutputStream bos = new ByteArrayOutputStream(input.length);
byte[] buf = new byte[1024];
while (!compressor.finished()) {
int count = compressor.deflate(buf);
bos.write(buf, 0, count);
}
bos.close();
byte[] compressedData = bos.toByteArray();
Inflater decompressor = new Inflater();
decompressor.setInput(compressedData);
bos = new ByteArrayOutputStream(compressedData.length);
buf = new byte[1024];
while (!decompressor.finished()) {
int count = decompressor.inflate(buf);
bos.write(buf, 0, count);
}
bos.close();
byte[] decompressedData = bos.toByteArray();
System.out.println(new String(decompressedData));
}
}
Determine whether a file is a ZIP File.
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.zip.ZipFile;
public class Main {
/**
* Determine whether a file is a ZIP File.
*/
public static boolean isZipFile(File file) throws IOException {
if(file.isDirectory()) {
return false;
}
if(!file.canRead()) {
throw new IOException("Cannot read file "+file.getAbsolutePath());
}
if(file.length() < 4) {
return false;
}
DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
int test = in.readInt();
in.close();
return test == 0x504b0304;
}
}
Displaying contents of a compressed zip file
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
public class ZipFileViewer extends JFrame {
private JTable m_zipTable;
private ZipTableModel m_zipTableModel;
public ZipFileViewer(String zipFile, List zipEntries) {
m_zipTableModel = new ZipTableModel(zipEntries);
m_zipTable = new JTable(m_zipTableModel);
JScrollPane scrollPane = new JScrollPane(m_zipTable);
m_zipTable.setShowVerticalLines(true);
m_zipTable.setShowHorizontalLines(false);
getContentPane().add(scrollPane);
setSize(800, 400);
setVisible(true);
}
public static void main(String[] arg) throws Exception {
String zipFileName = arg[0];
List zipFileList = null;
ZipFile zipFile = new ZipFile(zipFileName);
Enumeration zipEntries = zipFile.entries();
zipFileList = new ArrayList();
while (zipEntries.hasMoreElements()) {
zipFileList.add((ZipEntry) (zipEntries.nextElement()));
}
ZipFileViewer zipFileViewer = new ZipFileViewer(zipFileName, zipFileList);
}
}
class ZipTableModel extends AbstractTableModel {
public static final int NAME = 0;
public static final int SIZE = 1;
public static final int COMP_SIZE = 2;
public static final int TYPE = 3;
public static final int LAST_MODI = 4;
public String[] m_colNames = { "File Name", "Size", "Compressed Size", "Type", "Last Modified" };
private List m_zipEntries;
public ZipTableModel(List zipEntries) {
super();
m_zipEntries = zipEntries;
}
public int getColumnCount() {
return m_colNames.length;
}
public int getRowCount() {
return m_zipEntries.size();
}
public String getColumnName(int col) {
return m_colNames[col];
}
public Object getValueAt(int row, int col) {
ZipEntry zipEntry = (ZipEntry) (m_zipEntries.get(row));
switch (col) {
case NAME:
return zipEntry.getName();
case SIZE:
if (zipEntry.isDirectory()) {
return "";
} else {
return String.valueOf(zipEntry.getSize() / 1000) + " KB";
}
case COMP_SIZE:
if (zipEntry.isDirectory()) {
return "";
} else {
return String.valueOf(zipEntry.getCompressedSize() / 1000) + " KB";
}
case TYPE:
if (zipEntry.isDirectory()) {
return "Directory";
} else {
return "File";
}
case LAST_MODI:
return String.valueOf(new Date(zipEntry.getTime()));
}
return new String();
}
}
Extract contents of a zip file
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class Main {
public static void main(String[] args) throws Exception {
ZipInputStream inStream = new ZipInputStream(new FileInputStream("compressed.zip"));
OutputStream outStream = new FileOutputStream("extracted.txt");
byte[] buffer = new byte[1024];
int read;
ZipEntry entry ;
if ((entry = inStream.getNextEntry()) != null) {
while ((read = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, read);
}
}
outStream.close();
inStream.close();
}
}
Extract file/files from a zip file
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class Main {
public static void main(String[] args) throws Exception{
String destinationname = "d:\\";
byte[] buf = new byte[1024];
ZipInputStream zipinputstream = null;
ZipEntry zipentry;
zipinputstream = new ZipInputStream(new FileInputStream("fileName"));
zipentry = zipinputstream.getNextEntry();
while (zipentry != null) {
String entryName = zipentry.getName();
FileOutputStream fileoutputstream;
File newFile = new File(entryName);
String directory = newFile.getParent();
if (directory == null) {
if (newFile.isDirectory())
break;
}
fileoutputstream = new FileOutputStream(destinationname + entryName);
int n;
while ((n = zipinputstream.read(buf, 0, 1024)) > -1){
fileoutputstream.write(buf, 0, n);
}
fileoutputstream.close();
zipinputstream.closeEntry();
zipentry = zipinputstream.getNextEntry();
}
zipinputstream.close();
}
}
Extract zip file to destination folder
//The contents of this file are subject to the Mozilla Public License Version 1.1
//(the "License"); you may not use this file except in compliance with the
//License. You may obtain a copy of the License at http://www.mozilla.org/MPL/
//
//Software distributed under the License is distributed on an "AS IS" basis,
//WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
//for the specific language governing rights and
//limitations under the License.
//
//The Original Code is "The Columba Project"
//
//The Initial Developers of the Original Code are Frederik Dietz and Timo Stich.
//Portions created by Frederik Dietz and Timo Stich are Copyright (C) 2003.
//
//All Rights Reserved.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
* Zip archive operations are handled by this class.
*
* @author fdietz
*/
public class ZipFileIO {
/**
* No instances needed.
*/
private ZipFileIO() {
// don"t instantiate this class
}
/**
* Extract zip file to destination folder.
*
* @param file
* zip file to extract
* @param destination
* destinatin folder
*/
public static void extract(File file, File destination) throws IOException {
ZipInputStream in = null;
OutputStream out = null;
try {
// Open the ZIP file
in = new ZipInputStream(new FileInputStream(file));
// Get the first entry
ZipEntry entry = null;
while ((entry = in.getNextEntry()) != null) {
String outFilename = entry.getName();
// Open the output file
if (entry.isDirectory()) {
new File(destination, outFilename).mkdirs();
} else {
out = new FileOutputStream(new File(destination,
outFilename));
// Transfer bytes from the ZIP file to the output file
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
// Close the stream
out.close();
}
}
} finally {
// Close the stream
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
/**
* Return the first directory of this archive. This is needed to determine
* the plugin directory.
*
* @param zipFile
* @return <class>File</class> containing the first entry of this archive
*/
public static File getFirstFile(File zipFile) throws IOException {
ZipInputStream in = null;
try {
// Open the ZIP file
in = new ZipInputStream(new FileInputStream(zipFile));
// Get the first entry
ZipEntry entry = null;
while ((entry = in.getNextEntry()) != null) {
String outFilename = entry.getName();
if (entry.isDirectory()) {
return new File(outFilename);
}
}
} finally {
if (in != null) {
// Close the stream
in.close();
}
}
return null;
}
}
Listing the Contents of a ZIP File
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class Main {
public static void main(String[] argv) throws Exception {
ZipFile zf = new ZipFile("filename.zip");
for (Enumeration entries = zf.entries(); entries.hasMoreElements();) {
String zipEntryName = ((ZipEntry) entries.nextElement()).getName();
}
}
}
List the contents of a zip file
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class Main {
public static void main(String[] args) throws Exception {
ZipFile zipFile = new ZipFile("testfile.zip");
Enumeration zipEntries = zipFile.entries();
while (zipEntries.hasMoreElements()) {
System.out.println(((ZipEntry) zipEntries.nextElement()).getName());
}
}
}
List the entries of a zip file
import java.util.Date;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class Main {
public static void main(String[] args) throws Exception {
ZipFile zf = new ZipFile("a.zip");
Enumeration e = zf.entries();
while (e.hasMoreElements()) {
ZipEntry ze = (ZipEntry) e.nextElement();
String name = ze.getName();
long uncompressedSize = ze.getSize();
long compressedSize = ze.getCompressedSize();
long crc = ze.getCrc();
int method = ze.getMethod();
String comment = ze.getComment();
System.out.println(name + " was stored at " + new Date(ze.getTime()));
if (method == ZipEntry.STORED) {
System.out.println("with a size of " + uncompressedSize + " bytes");
} else if (method == ZipEntry.DEFLATED) {
System.out.println("from " + uncompressedSize + " bytes to " + compressedSize);
} else {
System.out.println("from " + uncompressedSize + " bytes to " + compressedSize);
}
System.out.println("Its CRC is " + crc);
if (comment != null && !comment.equals("")) {
System.out.println(comment);
}
if (ze.isDirectory()) {
System.out.println(name + " is a directory");
}
}
}
}
Load zip file and scan zip file
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class ZipTest {
public static void scanZipFile(String zipname) {
try {
ZipInputStream zin = new ZipInputStream(
new FileInputStream(zipname));
ZipEntry entry;
while ((entry = zin.getNextEntry()) != null) {
System.out.println(entry.getName());
zin.closeEntry();
}
zin.close();
} catch (IOException e) {
}
}
public static void loadZipFile(String zipname, String name) {
try {
ZipInputStream zin = new ZipInputStream(
new FileInputStream(zipname));
ZipEntry entry;
System.out.println("");
while ((entry = zin.getNextEntry()) != null) {
if (entry.getName().equals(name)) {
BufferedReader in = new BufferedReader(
new InputStreamReader(zin));
String s;
while ((s = in.readLine()) != null)
System.out.println(s + "\n");
}
zin.closeEntry();
}
zin.close();
} catch (IOException e) {
}
}
public static void main(String[] args) {
scanZipFile("Your zip file name here");
loadZipFile("zip file name", "file name");
}
}
Makes a zip file named xmlFileName from xmlURL at path
/**
* Copyright (c) 2003 Daffodil Software Ltd all rights reserved.
* This program is free software; you can redistribute it and/or modify
* it under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
* There are special exceptions to the terms and conditions of the GPL
* as it is applied to this software. See the GNU General Public License for more details.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
import java.io.*;
import java.util.zip.*;
/**
* This class is used to make zip file of the XML file,BLOB.lob and CLOB.lob
* so that compacted files can be transferred over the network. Besides it, this
* class contains method for unzipping it.
*/
public class ZipHandler
{
/**
* makes a zip file named <xmlFileName> from <xmlURL> at path <zipURL>
* @param zipURL
* @param xmlURL
* @param xmlFileName
*/
public static void makeZip(String zipURL, String xmlURL, String xmlFileName) throws
IOException
{
FileOutputStream fos = new FileOutputStream(new File(zipURL));
ZipOutputStream zos = new ZipOutputStream(fos);
// zos.setLevel();
FileInputStream fis = new FileInputStream(xmlURL);
zos.putNextEntry(new ZipEntry(xmlFileName+".xml"));
writeInOutputStream(fis,zos);
String bpath = "c:\\";
FileInputStream fisBLOB = createInputStream(bpath);
zos.putNextEntry(new ZipEntry("blob.lob"));
writeInOutputStream(fisBLOB, zos);
zos.closeEntry();
String cpath = "c:\\";
FileInputStream fisCLOB = createInputStream(cpath);
zos.putNextEntry(new ZipEntry("clob.lob"));
writeInOutputStream(fisCLOB, zos);
zos.closeEntry();
fis.close();
fisCLOB.close();
fisBLOB.close();
zos.close();
fos.close();
}
/**
* unzipps a zip file placed at <zipURL> to path <xmlURL>
* @param zipURL
* @param xmlURL
*/
public static void unZip(String zipURL, String xmlURL) throws IOException
{
FileOutputStream fosBLOB = new FileOutputStream(new File("c:\\"));
FileOutputStream fosCLOB = new FileOutputStream(new File("c:\\"));
FileInputStream fis = new FileInputStream(new File(zipURL));
ZipInputStream zis = new ZipInputStream(fis);
FileOutputStream fos = new FileOutputStream(xmlURL);
ZipEntry ze = zis.getNextEntry();
ExtractZip(zis, fos, fosBLOB, fosCLOB, ze);
ze = zis.getNextEntry();
ExtractZip(zis, fos, fosBLOB, fosCLOB, ze);
ze = zis.getNextEntry();
ExtractZip(zis, fos, fosBLOB, fosCLOB, ze);
fos.flush();
fis.close();
fos.close();
fosCLOB.close();
fosBLOB.close();
zis.close();
}
private static void ExtractZip(ZipInputStream zis, FileOutputStream fos,
FileOutputStream fosBLOB,
FileOutputStream fosCLOB, ZipEntry ze) throws
IOException {
if (ze.getName().equalsIgnoreCase("blob.lob"))
writeInOutputStream(zis, fosBLOB);
else if (ze.getName().equalsIgnoreCase("clob.lob"))
writeInOutputStream(zis, fosCLOB);
else
writeInOutputStream(zis, fos);
}
private static void writeInOutputStream(InputStream is,
OutputStream os) throws
IOException {
byte[] buf = new byte[1024];
int len = 0;
while ( (len = is.read(buf)) > 0)
{
os.write(buf, 0, len);
}
}
/**
* makes a zip file named <xmlFileName> from <xmlURL> at path <zipURL>
* @param zipURL
* @param xmlURL
* @param xmlFileName
*/
public static void makeStructZip(String zipURL, String xmlURL, String xmlFileName) throws
IOException
{
FileOutputStream fos = new FileOutputStream(new File(zipURL));
ZipOutputStream zos = new ZipOutputStream(fos);
// zos.setLevel();
FileInputStream fis = new FileInputStream(xmlURL);
zos.putNextEntry(new ZipEntry(xmlFileName+".xml"));
writeInOutputStream(fis,zos);
zos.closeEntry();
fis.close();
zos.close();
}
/**
* unzipps a zip file placed at <zipURL> to path <xmlURL>
* @param zipURL
* @param xmlURL
*/
public static void unStructZip(String zipURL, String xmlURL) throws IOException
{
FileInputStream fis = new FileInputStream(new File(zipURL));
ZipInputStream zis = new ZipInputStream(fis);
FileOutputStream fos = new FileOutputStream(xmlURL);
ZipEntry ze = zis.getNextEntry();
writeInOutputStream(zis,fos);
fos.flush();
fis.close();
fos.close();
zis.close();
}
private static FileInputStream createInputStream(String bpath) throws IOException{
FileInputStream fis = null;
try
{
fis = new FileInputStream(bpath);
}
catch (FileNotFoundException ex)
{
FileOutputStream temp = new FileOutputStream(bpath);
fis = new FileInputStream(bpath);
}
return fis;
}
}
Making a zip file of directory including its subdirectories recursively
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class Main {
private static void zipDir(String zipFileName, String dir) throws Exception {
File dirObj = new File(dir);
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
System.out.println("Creating : " + zipFileName);
addDir(dirObj, out);
out.close();
}
static void addDir(File dirObj, ZipOutputStream out) throws IOException {
File[] files = dirObj.listFiles();
byte[] tmpBuf = new byte[1024];
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
addDir(files[i], out);
continue;
}
FileInputStream in = new FileInputStream(files[i].getAbsolutePath());
System.out.println(" Adding: " + files[i].getAbsolutePath());
out.putNextEntry(new ZipEntry(files[i].getAbsolutePath()));
int len;
while ((len = in.read(tmpBuf)) > 0) {
out.write(tmpBuf, 0, len);
}
out.closeEntry();
in.close();
}
}
public static void main(String[] args) throws Exception {
zipDir(args[0], args[1]);
}
}
Package files utility
/* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Repackage {
public static void main(String[] args) throws Exception {
new Repackage(args).repackage();
}
private Repackage(String[] args) {
String sourceDir = null;
String targetDir = null;
String repackageSpec = null;
boolean failure = false;
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-repackage") && i + 1 < args.length)
repackageSpec = args[++i];
else if (args[i].equals("-f") && i + 1 < args.length)
sourceDir = args[++i];
else if (args[i].equals("-t") && i + 1 < args.length)
targetDir = args[++i];
else
failure = true;
}
if (failure || repackageSpec == null || (sourceDir == null ^ targetDir == null))
throw new RuntimeException(
"Usage: repackage -repackage [spec] [ -f [sourcedir] -t [targetdir] ]");
_repackager = new Repackager(repackageSpec);
if (sourceDir == null || targetDir == null)
return;
_sourceBase = new File(sourceDir);
_targetBase = new File(targetDir);
}
public void repackage() throws Exception {
if (_sourceBase == null || _targetBase == null) { // read from system.in,
// write on system.out
System.out.println(_repackager.repackage(readInputStream(System.in)).toString());
return;
}
_fromPackages = _repackager.getFromPackages();
_toPackages = _repackager.getToPackages();
_packagePattern = Pattern.rupile("^\\s*package\\s+((?:\\w|\\.)*)\\s*;", Pattern.MULTILINE);
_moveAlongFiles = new ArrayList();
_movedDirs = new HashMap();
// System.out.println( "Deleting repackage dir ..." );
// recursiveDelete( _targetBase );
_targetBase.mkdirs();
ArrayList files = new ArrayList();
fillFiles(files, _sourceBase);
System.out.println("Repackaging " + files.size() + " files ...");
int prefixLength = _sourceBase.getCanonicalPath().length();
for (int i = 0; i < files.size(); i++) {
File from = (File) files.get(i);
String name = from.getCanonicalPath().substring(prefixLength + 1);
repackageFile(name);
}
finishMovingFiles();
if (_skippedFiles > 0)
System.out.println("Skipped " + _skippedFiles + " unmodified files.");
}
private boolean fileIsUnchanged(String name) {
File sourceFile = new File(_sourceBase, name);
File targetFile = new File(_targetBase, name);
return (sourceFile.lastModified() < targetFile.lastModified());
}
public void repackageFile(String name) throws IOException {
if (name.endsWith(".java"))
repackageJavaFile(name);
else if (name.endsWith(".xsdconfig") || name.endsWith(".xml") || name.endsWith(".g"))
repackageNonJavaFile(name);
else if (name.startsWith("bin" + File.separatorChar))
repackageNonJavaFile(name);
else
moveAlongWithJavaFiles(name);
}
public void moveAlongWithJavaFiles(String name) {
_moveAlongFiles.add(name);
}
public void finishMovingFiles() throws IOException {
for (Iterator i = _moveAlongFiles.iterator(); i.hasNext();) {
String name = (String) i.next();
String toName = name;
String srcDir = Repackager.dirForPath(name);
String toDir = (String) _movedDirs.get(srcDir);
if (toDir != null)
toName = new File(toDir, new File(name).getName()).toString();
if (name.endsWith(".html"))
repackageNonJavaFile(name, toName);
else
justMoveNonJavaFile(name, toName);
}
}
public void repackageNonJavaFile(String name) throws IOException {
File sourceFile = new File(_sourceBase, name);
File targetFile = new File(_targetBase, name);
if (sourceFile.lastModified() < targetFile.lastModified())
_skippedFiles += 1;
else
writeFile(targetFile, _repackager.repackage(readFile(sourceFile)));
}
public void repackageNonJavaFile(String sourceName, String targetName) throws IOException {
File sourceFile = new File(_sourceBase, sourceName);
File targetFile = new File(_targetBase, targetName);
if (sourceFile.lastModified() < targetFile.lastModified())
_skippedFiles += 1;
else
writeFile(targetFile, _repackager.repackage(readFile(sourceFile)));
}
public void justMoveNonJavaFile(String sourceName, String targetName) throws IOException {
File sourceFile = new File(_sourceBase, sourceName);
File targetFile = new File(_targetBase, targetName);
if (sourceFile.lastModified() < targetFile.lastModified())
_skippedFiles += 1;
else
copyFile(sourceFile, targetFile);
}
public void repackageJavaFile(String name) throws IOException {
File sourceFile = new File(_sourceBase, name);
StringBuffer sb = readFile(sourceFile);
Matcher packageMatcher = _packagePattern.matcher(sb);
if (packageMatcher.find()) {
String pkg = packageMatcher.group(1);
int pkgStart = packageMatcher.start(1);
int pkgEnd = packageMatcher.end(1);
if (packageMatcher.find())
throw new RuntimeException("Two package specifications found: " + name);
List filePath = Repackager.splitPath(name, File.separatorChar);
String srcDir = Repackager.dirForPath(name);
// Sort the repackage spec so that longer from"s are first to match
// longest package first
for (;;) {
boolean swapped = false;
for (int i = 1; i < filePath.size(); i++) {
String spec1 = (String) filePath.get(i - 1);
String spec2 = (String) filePath.get(i);
if (spec1.indexOf(":") < spec2.indexOf(":")) {
filePath.set(i - 1, spec2);
filePath.set(i, spec1);
swapped = true;
}
}
if (!swapped)
break;
}
List pkgPath = Repackager.splitPath(pkg, ".");
int f = filePath.size() - 2;
if (f < 0 || (filePath.size() - 1) < pkgPath.size())
throw new RuntimeException("Package spec differs from file path: " + name);
for (int i = pkgPath.size() - 1; i >= 0; i--) {
if (!pkgPath.get(i).equals(filePath.get(f)))
throw new RuntimeException("Package spec differs from file path: " + name);
f--;
}
List changeTo = null;
List changeFrom = null;
from: for (int i = 0; i < _fromPackages.size(); i++) {
List from = (List) _fromPackages.get(i);
if (from.size() <= pkgPath.size()) {
for (int j = 0; j < from.size(); j++)
if (!from.get(j).equals(pkgPath.get(j)))
continue from;
changeFrom = from;
changeTo = (List) _toPackages.get(i);
break;
}
}
if (changeTo != null) {
String newPkg = "";
String newName = "";
for (int i = 0; i < changeTo.size(); i++) {
if (i > 0) {
newPkg += ".";
newName += File.separatorChar;
}
newPkg += changeTo.get(i);
newName += changeTo.get(i);
}
for (int i = filePath.size() - pkgPath.size() - 2; i >= 0; i--)
newName = (String) filePath.get(i) + File.separatorChar + newName;
for (int i = changeFrom.size(); i < pkgPath.size(); i++) {
newName += File.separatorChar + (String) pkgPath.get(i);
newPkg += "." + (String) pkgPath.get(i);
}
newName += File.separatorChar + (String) filePath.get(filePath.size() - 1);
sb.replace(pkgStart, pkgEnd, newPkg);
name = newName;
String newDir = Repackager.dirForPath(name);
if (!srcDir.equals(newDir)) {
_movedDirs.put(srcDir, newDir);
}
}
}
File targetFile = new File(_targetBase, name); // new name
if (sourceFile.lastModified() < targetFile.lastModified()) {
_skippedFiles += 1;
return;
}
writeFile(new File(_targetBase, name), _repackager.repackage(sb));
}
void writeFile(File f, StringBuffer chars) throws IOException {
f.getParentFile().mkdirs();
OutputStream out = new FileOutputStream(f);
Writer w = new OutputStreamWriter(out);
Reader r = new StringReader(chars.toString());
copy(r, w);
r.close();
w.close();
out.close();
}
StringBuffer readFile(File f) throws IOException {
InputStream in = new FileInputStream(f);
Reader r = new InputStreamReader(in);
StringWriter w = new StringWriter();
copy(r, w);
w.close();
r.close();
in.close();
return w.getBuffer();
}
StringBuffer readInputStream(InputStream is) throws IOException {
Reader r = new InputStreamReader(is);
StringWriter w = new StringWriter();
copy(r, w);
w.close();
r.close();
return w.getBuffer();
}
public static void copyFile(File from, File to) throws IOException {
to.getParentFile().mkdirs();
FileInputStream in = new FileInputStream(from);
FileOutputStream out = new FileOutputStream(to);
copy(in, out);
out.close();
in.close();
}
public static void copy(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024 * 16];
for (;;) {
int n = in.read(buffer, 0, buffer.length);
if (n < 0)
break;
out.write(buffer, 0, n);
}
}
public static void copy(Reader r, Writer w) throws IOException {
char[] buffer = new char[1024 * 16];
for (;;) {
int n = r.read(buffer, 0, buffer.length);
if (n < 0)
break;
w.write(buffer, 0, n);
}
}
public void fillFiles(ArrayList files, File file) throws IOException {
if (!file.isDirectory()) {
files.add(file);
return;
}
// Exclude the build directory
if (file.getName().equals("build"))
return;
// Exclude CVS directories
if (file.getName().equals("CVS"))
return;
String[] entries = file.list();
for (int i = 0; i < entries.length; i++)
fillFiles(files, new File(file, entries[i]));
}
public void recursiveDelete(File file) throws IOException {
if (!file.exists())
return;
if (file.isDirectory()) {
String[] entries = file.list();
for (int i = 0; i < entries.length; i++)
recursiveDelete(new File(file, entries[i]));
}
file.delete();
}
private File _sourceBase;
private File _targetBase;
private List _fromPackages;
private List _toPackages;
private Pattern _packagePattern;
private Repackager _repackager;
private Map _movedDirs;
private List _moveAlongFiles;
private int _skippedFiles;
}
/*
* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class Repackager {
public Repackager(String repackageSpecs) {
_fromPackages = new ArrayList();
_toPackages = new ArrayList();
List repackages = splitPath(repackageSpecs, ";");
// Sort the repackage spec so that longer from"s are first to match
// longest package first
for (;;) {
boolean swapped = false;
for (int i = 1; i < repackages.size(); i++) {
String spec1 = (String) repackages.get(i - 1);
String spec2 = (String) repackages.get(i);
if (spec1.indexOf(":") < spec2.indexOf(":")) {
repackages.set(i - 1, spec2);
repackages.set(i, spec1);
swapped = true;
}
}
if (!swapped)
break;
}
for (int i = 0; i < repackages.size(); i++) {
String spec = (String) repackages.get(i);
int j = spec.indexOf(":");
if (j < 0 || spec.indexOf(":", j + 1) >= 0)
throw new RuntimeException("Illegal repackage specification: " + spec);
String from = spec.substring(0, j);
String to = spec.substring(j + 1);
_fromPackages.add(Repackager.splitPath(from, "."));
_toPackages.add(Repackager.splitPath(to, "."));
}
_fromMatchers = new Matcher[_fromPackages.size() * 2];
_toPackageNames = new String[_fromPackages.size() * 2];
addPatterns(".", 0);
addPatterns("/", _fromPackages.size());
}
void addPatterns(char sep, int off) {
for (int i = 0; i < _fromPackages.size(); i++) {
List from = (List) _fromPackages.get(i);
List to = (List) _toPackages.get(i);
String pattern = "";
for (int j = 0; j < from.size(); j++) {
if (j > 0)
pattern += "\\" + sep;
pattern += from.get(j);
}
String toPackage = "";
for (int j = 0; j < to.size(); j++) {
if (j > 0)
toPackage += sep;
toPackage += to.get(j);
}
_fromMatchers[off + i] = Pattern.rupile(pattern).matcher("");
_toPackageNames[off + i] = toPackage;
}
}
public StringBuffer repackage(StringBuffer sb) {
StringBuffer result = null;
for (int i = 0; i < _fromMatchers.length; i++) {
Matcher m = (Matcher) _fromMatchers[i];
m.reset(sb);
for (boolean found = m.find(); found; found = m.find()) {
if (result == null)
result = new StringBuffer();
m.appendReplacement(result, _toPackageNames[i]);
}
if (result != null) {
m.appendTail(result);
sb = result;
result = null;
}
}
return sb;
}
public List getFromPackages() {
return _fromPackages;
}
public List getToPackages() {
return _toPackages;
}
public static ArrayList splitPath(String path, char separator) {
ArrayList components = new ArrayList();
for (;;) {
int i = path.indexOf(separator);
if (i < 0)
break;
components.add(path.substring(0, i));
path = path.substring(i + 1);
}
if (path.length() > 0)
components.add(path);
return components;
}
public static String dirForPath(String path) {
return new File(path).getParent();
}
private List _fromPackages;
private List _toPackages;
private Matcher[] _fromMatchers;
private String[] _toPackageNames;
}
Provides both writing and reading from a file which is transparently compressed in Zip
//----------------------------------------------------------------------------//
// //
// Z i p //
// //
// Copyright (C) Herve Bitteur 2000-2009. All rights reserved. //
// This software is released under the GNU General Public License. //
// Please contact users@audiveris.dev.java.net to report bugs & suggestions. //
//----------------------------------------------------------------------------//
//
import java.io.*;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
/**
* Class <code>Zip</code> is a convenient utility that provides both writing and
* reading from a file which is transparently compressed in Zip.
*
* @author Hervé Bitteur
* @version $Id: Zip.java,v 1.6 2009/03/03 19:45:51 hbitteur Exp $
*/
public class Zip
{
//~ Methods ----------------------------------------------------------------
//--------------------//
// createInputStream //
//-------------------//
/**
* Create a InputStream on a given file, by looking for a zip archive whose
* path is the file path with ".zip" appended, and by reading the first
* entry in this zip file.
*
* @param file the file (with no zip extension)
*
* @return a InputStream on the zip entry
*/
public static InputStream createInputStream (File file)
{
try {
String path = file.getCanonicalPath();
//ZipFile zf = new ZipFile(path + ".zip");
ZipFile zf = new ZipFile(path);
for (Enumeration entries = zf.entries(); entries.hasMoreElements();) {
ZipEntry entry = (ZipEntry) entries.nextElement();
return zf.getInputStream(entry);
}
} catch (FileNotFoundException ex) {
System.err.println(ex.toString());
System.err.println(file + " not found");
} catch (IOException ex) {
System.err.println(ex.toString());
}
return null;
}
//--------------------//
// createOutputStream //
//-------------------//
/**
* Create a OutputStream on a given file, transparently compressing the data
* to a Zip file whose name is the provided file path, with a ".zip"
* extension added.
*
* @param file the file (with no zip extension)
*
* @return a OutputStream on the zip entry
*/
public static OutputStream createOutputStream (File file)
{
try {
String path = file.getCanonicalPath();
FileOutputStream fos = new FileOutputStream(path + ".zip");
ZipOutputStream zos = new ZipOutputStream(fos);
ZipEntry ze = new ZipEntry(file.getName());
zos.putNextEntry(ze);
return zos;
} catch (FileNotFoundException ex) {
System.err.println(ex.toString());
System.err.println(file + " not found");
} catch (Exception ex) {
System.err.println(ex.toString());
}
return null;
}
//--------------//
// createReader //
//--------------//
/**
* Create a Reader on a given file, by looking for a zip archive whose path
* is the file path with ".zip" appended, and by reading the first entry in
* this zip file.
*
* @param file the file (with no zip extension)
*
* @return a reader on the zip entry
*/
public static Reader createReader (File file)
{
try {
String path = file.getCanonicalPath();
ZipFile zf = new ZipFile(path + ".zip");
for (Enumeration entries = zf.entries(); entries.hasMoreElements();) {
ZipEntry entry = (ZipEntry) entries.nextElement();
InputStream is = zf.getInputStream(entry);
return new InputStreamReader(is);
}
} catch (FileNotFoundException ex) {
System.err.println(ex.toString());
System.err.println(file + " not found");
} catch (IOException ex) {
System.err.println(ex.toString());
}
return null;
}
//--------------//
// createWriter //
//--------------//
/**
* Create a Writer on a given file, transparently compressing the data to a
* Zip file whose name is the provided file path, with a ".zip" extension
* added.
*
* @param file the file (with no zip extension)
*
* @return a writer on the zip entry
*/
public static Writer createWriter (File file)
{
try {
String path = file.getCanonicalPath();
FileOutputStream fos = new FileOutputStream(path + ".zip");
ZipOutputStream zos = new ZipOutputStream(fos);
ZipEntry ze = new ZipEntry(file.getName());
zos.putNextEntry(ze);
return new OutputStreamWriter(zos);
} catch (FileNotFoundException ex) {
System.err.println(ex.toString());
System.err.println(file + " not found");
} catch (Exception ex) {
System.err.println(ex.toString());
}
return null;
}
}
Put file To Zip File
/*
* Copyright 2004 Outerthought bvba and Schaubroeck nv
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// revised from outerj daisy
import java.io.*;
import java.util.zip.ZipOutputStream;
import java.util.zip.ZipEntry;
public class ZipHelper {
private static int BUFFER_SIZE = 32768;
public static void fileToZip(File file, File zipFile, int compressionLevel) throws Exception {
zipFile.createNewFile();
FileOutputStream fout = new FileOutputStream(zipFile);
ZipOutputStream zout = null;
try {
zout = new ZipOutputStream(new BufferedOutputStream(fout));
zout.setLevel(compressionLevel);
if (file.isDirectory()) {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++)
fileToZip(files[i], zout, file);
} else if (file.isFile()) {
fileToZip(file, zout, file.getParentFile());
}
} finally {
if (zout != null)
zout.close();
}
}
private static void fileToZip(File file, ZipOutputStream zout, File baseDir) throws Exception {
String entryName = file.getPath().substring(baseDir.getPath().length() + 1);
if (File.separatorChar != "/")
entryName = entryName.replace(File.separator, "/");
if (file.isDirectory()) {
zout.putNextEntry(new ZipEntry(entryName + "/"));
zout.closeEntry();
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++)
fileToZip(files[i], zout, baseDir);
} else {
FileInputStream is = null;
try {
is = new FileInputStream(file);
zout.putNextEntry(new ZipEntry(entryName));
streamCopy(is, zout);
} finally {
zout.closeEntry();
if (is != null)
is.close();
}
}
}
private static void streamCopy(InputStream is, OutputStream os) throws IOException {
byte[] buffer = new byte[BUFFER_SIZE];
int len;
while ((len = is.read(buffer)) > 0) {
os.write(buffer, 0, len);
}
}
}
Read a zip file checksum value
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.Adler32;
import java.util.zip.CheckedInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class Main {
public static void main(String[] args) throws Exception {
String zipname = "d.zip";
CheckedInputStream checksum = new CheckedInputStream(
new FileInputStream(zipname), new Adler32());
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(checksum));
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
System.out.println("Unzipping: " + entry.getName());
int size;
byte[] buffer = new byte[2048];
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(entry.getName()), buffer.length);
while ((size = zis.read(buffer, 0, buffer.length)) != -1) {
bos.write(buffer, 0, size);
}
bos.flush();
bos.close();
}
zis.close();
System.out.println("Checksum = " + checksum.getChecksum().getValue());
}
}
Read entries in a zip / compressed file
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class Main {
public static void main(String[] args) throws Exception {
ZipFile zip = new ZipFile(new File("sample.zip"));
for (Enumeration e = zip.entries(); e.hasMoreElements();) {
ZipEntry entry = (ZipEntry) e.nextElement();
System.out.println("File name: " + entry.getName() + "; size: " + entry.getSize()
+ "; compressed size: " + entry.getCompressedSize());
InputStream is = zip.getInputStream(entry);
InputStreamReader isr = new InputStreamReader(is);
char[] buffer = new char[1024];
while (isr.read(buffer, 0, buffer.length) != -1) {
String s = new String(buffer);
System.out.println(s.trim());
}
}
}
}
Read files within a zip file
import java.io.File;
import java.io.FileInputStream;
import java.io.RandomAccessFile;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class Main {
public static void main(String[] args) throws Exception{
ZipInputStream zipinputstream = new ZipInputStream(new FileInputStream("filename"));
ZipEntry zipentry = zipinputstream.getNextEntry();
while (zipentry != null) {
String entryName = zipentry.getName();
File newFile = new File(entryName);
String directory = newFile.getParent();
if (directory == null) {
if (newFile.isDirectory())
break;
}
RandomAccessFile rf = new RandomAccessFile(entryName, "r");
String line;
if ((line = rf.readLine()) != null) {
System.out.println(line);
}
rf.close();
zipinputstream.closeEntry();
zipentry = zipinputstream.getNextEntry();
}
zipinputstream.close();
}
}
Reading the Contents of a ZIP File
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class ReadZip {
public static void main(String args[]) {
try {
ZipFile zf = new ZipFile("ReadZip.zip");
Enumeration entries = zf.entries();
BufferedReader input = new BufferedReader(new InputStreamReader(
System.in));
while (entries.hasMoreElements()) {
ZipEntry ze = (ZipEntry) entries.nextElement();
System.out.println("Read " + ze.getName() + "?");
String inputLine = input.readLine();
if (inputLine.equalsIgnoreCase("yes")) {
long size = ze.getSize();
if (size > 0) {
System.out.println("Length is " + size);
BufferedReader br = new BufferedReader(
new InputStreamReader(zf.getInputStream(ze)));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Read the content of a zip file ZipFile
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class Main {
public static void main(String[] args) throws IOException {
ZipFile zf = new ZipFile("a.zip");
Enumeration e = zf.entries();
while (e.hasMoreElements()) {
ZipEntry ze = (ZipEntry) e.nextElement();
FileOutputStream fout = new FileOutputStream(ze.getName());
InputStream in = zf.getInputStream(ze);
for (int c = in.read(); c != -1; c = in.read()) {
fout.write(c);
}
in.close();
fout.close();
}
}
}
Read zip file
import java.io.FileInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class Main {
public static void main(String[] args) throws Exception {
FileInputStream fis = new FileInputStream("C:/MyZip.zip");
ZipInputStream zis = new ZipInputStream(fis);
ZipEntry ze;
while ((ze = zis.getNextEntry()) != null) {
System.out.println(ze.getName());
zis.closeEntry();
}
zis.close();
}
}
Retrieve a compressed file from a ZIP file
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.zip.ZipInputStream;
public class Main {
public static void main(String[] argv) throws Exception {
ZipInputStream in = new ZipInputStream(new FileInputStream("source.zip"));
OutputStream out = new FileOutputStream("target");
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.close();
in.close();
}
}
Retrieve the contents of a ZIP file
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class Main {
public static void main(String[] argv) throws Exception {
ZipFile sourcefile = new ZipFile("source.zip");
for (Enumeration entries = sourcefile.entries(); entries.hasMoreElements();) {
String zipEntryName = ((ZipEntry) entries.nextElement()).getName();
System.out.println(zipEntryName);
}
}
}
Retrieving a Compressed File from a ZIP File
This example reads a ZIP file and decompresses the first entry.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class Main {
public static void main(String[] argv) throws Exception {
String inFilename = "infile.zip";
ZipInputStream in = new ZipInputStream(new FileInputStream(inFilename));
ZipEntry entry = in.getNextEntry();
String outFilename = "o";
OutputStream out = new FileOutputStream(outFilename);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.close();
in.close();
}
}
Return the first directory of this archive. This is needed to determine the plugin directory
//The contents of this file are subject to the Mozilla Public License Version 1.1
//(the "License"); you may not use this file except in compliance with the
//License. You may obtain a copy of the License at http://www.mozilla.org/MPL/
//
//Software distributed under the License is distributed on an "AS IS" basis,
//WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
//for the specific language governing rights and
//limitations under the License.
//
//The Original Code is "The Columba Project"
//
//The Initial Developers of the Original Code are Frederik Dietz and Timo Stich.
//Portions created by Frederik Dietz and Timo Stich are Copyright (C) 2003.
//
//All Rights Reserved.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
* Zip archive operations are handled by this class.
*
* @author fdietz
*/
public class ZipFileIO {
/**
* No instances needed.
*/
private ZipFileIO() {
// don"t instantiate this class
}
/**
* Extract zip file to destination folder.
*
* @param file
* zip file to extract
* @param destination
* destinatin folder
*/
public static void extract(File file, File destination) throws IOException {
ZipInputStream in = null;
OutputStream out = null;
try {
// Open the ZIP file
in = new ZipInputStream(new FileInputStream(file));
// Get the first entry
ZipEntry entry = null;
while ((entry = in.getNextEntry()) != null) {
String outFilename = entry.getName();
// Open the output file
if (entry.isDirectory()) {
new File(destination, outFilename).mkdirs();
} else {
out = new FileOutputStream(new File(destination,
outFilename));
// Transfer bytes from the ZIP file to the output file
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
// Close the stream
out.close();
}
}
} finally {
// Close the stream
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
/**
* Return the first directory of this archive. This is needed to determine
* the plugin directory.
*
* @param zipFile
* @return <class>File</class> containing the first entry of this archive
*/
public static File getFirstFile(File zipFile) throws IOException {
ZipInputStream in = null;
try {
// Open the ZIP file
in = new ZipInputStream(new FileInputStream(zipFile));
// Get the first entry
ZipEntry entry = null;
while ((entry = in.getNextEntry()) != null) {
String outFilename = entry.getName();
if (entry.isDirectory()) {
return new File(outFilename);
}
}
} finally {
if (in != null) {
// Close the stream
in.close();
}
}
return null;
}
}
Tape Archive Lister: Tar file
/*
* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java
* language and environment is gratefully acknowledged.
*
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/
/*
Error handling throughout. In particular, the reading code needs to checksum!
Write getInputStream(). Here"s how: seek on the file, malloc a buffer
big enough to hold the file, read it into memory, return a
ByteArrayInputStream.
Handle LF_LINK linked files: getEntry(name).getOffset().
Think about writing Tar files?
*/
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Vector;
/**
* Demonstrate the Tar archive lister.
*
* @author Ian F. Darwin, http://www.darwinsys.ru/
* @version $Id: TarList.java,v 1.7 2004/03/07 17:47:35 ian Exp $
*/
public class TarList {
public static void main(String[] argv) throws IOException, TarException {
if (argv.length == 0) {
System.err.println("Usage: TarList archive");
System.exit(1);
}
new TarList(argv[0]).list();
}
/** The TarFile we are reading */
TarFile tf;
/** Constructor */
public TarList(String fileName) {
tf = new TarFile(fileName);
}
/** Generate and print the listing */
public void list() throws IOException, TarException {
Enumeration list = tf.entries();
while (list.hasMoreElements()) {
TarEntry e = (TarEntry) list.nextElement();
System.out.println(toListFormat(e));
}
}
protected StringBuffer sb;
/** Shift used in formatting permissions */
protected static int[] shft = { 6, 3, 0 };
/** Format strings used in permissions */
protected static String rwx[] = { "---", "--x", "-w-", "-wx", "r--", "r-x",
"rw-", "rwx" };
/** NumberFormat used in formatting List form string */
NumberFormat sizeForm = new DecimalFormat("00000000");
/** Date used in printing mtime */
Date date = new Date();
SimpleDateFormat dateForm = new SimpleDateFormat("yyyy-MM-dd HH:mm");
/** Format a TarEntry the same way that UNIX tar does */
public String toListFormat(TarEntry e) {
sb = new StringBuffer();
switch (e.type) {
case TarEntry.LF_OLDNORMAL:
case TarEntry.LF_NORMAL:
case TarEntry.LF_CONTIG:
case TarEntry.LF_LINK: // hard link: same as file
sb.append("-"); // "f" would be sensible
break;
case TarEntry.LF_DIR:
sb.append("d");
break;
case TarEntry.LF_SYMLINK:
sb.append("l");
break;
case TarEntry.LF_CHR: // UNIX character device file
sb.append("c");
break;
case TarEntry.LF_BLK: // UNIX block device file
sb.append("b");
break;
case TarEntry.LF_FIFO: // UNIX named pipe
sb.append("p");
break;
default: // Can"t happen?
sb.append("?");
break;
}
// Convert e.g., 754 to rwxrw-r--
int mode = e.getMode();
for (int i = 0; i < 3; i++) {
sb.append(rwx[mode >> shft[i] & 007]);
}
sb.append(" ");
// owner and group
sb.append(e.getUname()).append("/").append(e.getGname()).append(" ");
// size
// DecimalFormat can"t do "%-9d", so we do part of it ourselves
sb.append(" ");
String t = sizeForm.format(e.getSize());
boolean digit = false;
char c;
for (int i = 0; i < 8; i++) {
c = t.charAt(i);
if (!digit && i < (8 - 1) && c == "0")
sb.append(" "); // leading space
else {
digit = true;
sb.append(c);
}
}
sb.append(" ");
// mtime
// copy file"s mtime into Data object (after scaling
// from "sec since 1970" to "msec since 1970"), and format it.
date.setTime(1000 * e.getTime());
sb.append(dateForm.format(date)).append(" ");
sb.append(e.getName());
if (e.isLink())
sb.append(" link to ").append(e.getLinkName());
if (e.isSymLink())
sb.append(" -> ").append(e.getLinkName());
return sb.toString();
}
}
/**
* One entry in an archive file.
*
* @author Ian Darwin
* @version $Id: TarEntry.java,v 1.7 2004/03/06 21:16:19 ian Exp $
* @note Tar format info taken from John Gilmore"s public domain tar program,
* @(#)tar.h 1.21 87/05/01 Public Domain, which said: "Created 25 August 1985 by
* John Gilmore, ihnp4!hoptoad!gnu." John is now gnu@toad.ru, and by
* another path tar.h is GPL"d in GNU Tar.
*/
class TarEntry {
/** Where in the tar archive this entry"s HEADER is found. */
public long fileOffset = 0;
/** The maximum size of a name */
public static final int NAMSIZ = 100;
public static final int TUNMLEN = 32;
public static final int TGNMLEN = 32;
// Next fourteen fields constitute one physical record.
// Padded to TarFile.RECORDSIZE bytes on tape/disk.
// Lazy Evaluation: just read fields in raw form, only format when asked.
/** File name */
byte[] name = new byte[NAMSIZ];
/** permissions, e.g., rwxr-xr-x? */
byte[] mode = new byte[8];
/* user */
byte[] uid = new byte[8];
/* group */
byte[] gid = new byte[8];
/* size */
byte[] size = new byte[12];
/* UNIX modification time */
byte[] mtime = new byte[12];
/* checksum field */
byte[] chksum = new byte[8];
byte type;
byte[] linkName = new byte[NAMSIZ];
byte[] magic = new byte[8];
byte[] uname = new byte[TUNMLEN];
byte[] gname = new byte[TGNMLEN];
byte[] devmajor = new byte[8];
byte[] devminor = new byte[8];
// End of the physical data fields.
/* The magic field is filled with this if uname and gname are valid. */
public static final byte TMAGIC[] = {
// "u", "s", "t", "a", "r", " ", " ", "\0"
0, 0, 0, 0, 0, 0, 0x20, 0x20, 0 }; /* 7 chars and a null */
/* Type value for Normal file, Unix compatibility */
public static final int LF_OLDNORMAL = "\0";
/* Type value for Normal file */
public static final int LF_NORMAL = "0";
/* Type value for Link to previously dumped file */
public static final int LF_LINK = "1";
/* Type value for Symbolic link */
public static final int LF_SYMLINK = "2";
/* Type value for Character special file */
public static final int LF_CHR = "3";
/* Type value for Block special file */
public static final int LF_BLK = "4";
/* Type value for Directory */
public static final int LF_DIR = "5";
/* Type value for FIFO special file */
public static final int LF_FIFO = "6";
/* Type value for Contiguous file */
public static final int LF_CONTIG = "7";
/* Constructor that reads the entry"s header. */
public TarEntry(RandomAccessFile is) throws IOException, TarException {
fileOffset = is.getFilePointer();
// read() returns -1 at EOF
if (is.read(name) < 0)
throw new EOFException();
// Tar pads to block boundary with nulls.
if (name[0] == "\0")
throw new EOFException();
// OK, read remaining fields.
is.read(mode);
is.read(uid);
is.read(gid);
is.read(size);
is.read(mtime);
is.read(chksum);
type = is.readByte();
is.read(linkName);
is.read(magic);
is.read(uname);
is.read(gname);
is.read(devmajor);
is.read(devminor);
// Since the tar header is < 512, we need to skip it.
is
.skipBytes((int) (TarFile.RECORDSIZE - (is.getFilePointer() % TarFile.RECORDSIZE)));
// TODO if checksum() fails,
// throw new TarException("Failed to find next header");
}
/** Returns the name of the file this entry represents. */
public String getName() {
return new String(name).trim();
}
public String getTypeName() {
switch (type) {
case LF_OLDNORMAL:
case LF_NORMAL:
return "file";
case LF_LINK:
return "link w/in archive";
case LF_SYMLINK:
return "symlink";
case LF_CHR:
case LF_BLK:
case LF_FIFO:
return "special file";
case LF_DIR:
return "directory";
case LF_CONTIG:
return "contig";
default:
throw new IllegalStateException("TarEntry.getTypeName: type "
+ type + " invalid");
}
}
/** Returns the UNIX-specific "mode" (type+permissions) of the entry */
public int getMode() {
try {
return Integer.parseInt(new String(mode).trim(), 8) & 0777;
} catch (IllegalArgumentException e) {
return 0;
}
}
/** Returns the size of the entry */
public int getSize() {
try {
return Integer.parseInt(new String(size).trim(), 8);
} catch (IllegalArgumentException e) {
return 0;
}
}
/**
* Returns the name of the file this entry is a link to, or null if this
* entry is not a link.
*/
public String getLinkName() {
// if (isLink())
// return null;
return new String(linkName).trim();
}
/** Returns the modification time of the entry */
public long getTime() {
try {
return Long.parseLong(new String(mtime).trim(), 8);
} catch (IllegalArgumentException e) {
return 0;
}
}
/** Returns the string name of the userid */
public String getUname() {
return new String(uname).trim();
}
/** Returns the string name of the group id */
public String getGname() {
return new String(gname).trim();
}
/** Returns the numeric userid of the entry */
public int getuid() {
try {
return Integer.parseInt(new String(uid).trim());
} catch (IllegalArgumentException e) {
return -1;
}
}
/** Returns the numeric gid of the entry */
public int getgid() {
try {
return Integer.parseInt(new String(gid).trim());
} catch (IllegalArgumentException e) {
return -1;
}
}
/** Returns true if this entry represents a file */
boolean isFile() {
return type == LF_NORMAL || type == LF_OLDNORMAL;
}
/** Returns true if this entry represents a directory */
boolean isDirectory() {
return type == LF_DIR;
}
/** Returns true if this a hard link (to a file in the archive) */
boolean isLink() {
return type == LF_LINK;
}
/** Returns true if this a symbolic link */
boolean isSymLink() {
return type == LF_SYMLINK;
}
/** Returns true if this entry represents some type of UNIX special file */
boolean isSpecial() {
return type == LF_CHR || type == LF_BLK || type == LF_FIFO;
}
public String toString() {
return "TarEntry[" + getName() + "]";
}
}
/*
* Exception for TarFile and TarEntry. $Id: TarException.java,v 1.3 1999/10/06
* 15:13:53 ian Exp $
*/
class TarException extends java.io.IOException {
public TarException() {
super();
}
public TarException(String msg) {
super(msg);
}
}
/**
* Tape Archive Lister, patterned loosely after java.util.ZipFile. Since, unlike
* Zip files, there is no central directory, you have to read the entire file
* either to be sure of having a particular file"s entry, or to know how many
* entries there are in the archive.
*
* @author Ian Darwin, http://www.darwinsys.ru/
* @version $Id: TarFile.java,v 1.12 2004/03/07 17:53:15 ian Exp $
*/
class TarFile {
/** True after we"ve done the expensive read. */
protected boolean read = false;
/** The list of entries found in the archive */
protected Vector list;
/** Size of header block. */
public static final int RECORDSIZE = 512;
/* Size of each block, in records */
protected int blocking;
/* Size of each block, in bytes */
protected int blocksize;
/** File containing archive */
protected String fileName;
/** Construct (open) a Tar file by name */
public TarFile(String name) {
fileName = name;
list = new Vector();
}
/** Construct (open) a Tar file by File */
public TarFile(java.io.File name) throws IOException {
this(name.getCanonicalPath());
}
/** The main datastream. */
protected RandomAccessFile is;
/**
* Read the Tar archive in its entirety. This is semi-lazy evaluation, in
* that we don"t read the file until we need to. A future revision may use
* even lazier evaluation: in getEntry, scan the list and, if not found,
* continue reading! For now, just read the whole file.
*/
protected void readFile() throws IOException, TarException {
is = new RandomAccessFile(fileName, "r");
TarEntry hdr;
try {
do {
hdr = new TarEntry(is);
if (hdr.getSize() < 0) {
System.out.println("Size < 0");
break;
}
// System.out.println(hdr.toString());
list.addElement(hdr);
// Get the size of the entry
int nbytes = hdr.getSize(), diff;
// Round it up to blocksize.
if ((diff = (nbytes % RECORDSIZE)) != 0) {
nbytes += RECORDSIZE - diff;
}
// And skip over the data portion.
// System.out.println("Skipping " + nbytes + " bytes");
is.skipBytes(nbytes);
} while (true);
} catch (EOFException e) {
// OK, just stop reading.
}
// All done, say we"ve read the contents.
read = true;
}
/* Close the Tar file. */
public void close() {
try {
is.close();
} catch (IOException e) {
// nothing to do
}
}
/* Returns an enumeration of the Tar file entries. */
public Enumeration entries() throws IOException, TarException {
if (!read) {
readFile();
}
return list.elements();
}
/** Returns the Tar entry for the specified name, or null if not found. */
public TarEntry getEntry(String name) {
for (int i = 0; i < list.size(); i++) {
TarEntry e = (TarEntry) list.elementAt(i);
if (name.equals(e.getName()))
return e;
}
return null;
}
/**
* Returns an InputStream for reading the contents of the specified entry
* from the archive. May cause the entire file to be read.
*/
public InputStream getInputStream(TarEntry entry) {
return null;
}
/** Returns the path name of the Tar file. */
public String getName() {
return fileName;
}
/**
* Returns the number of entries in the Tar archive. May cause the entire
* file to be read. XXX Obviously not written yet, sorry.
*/
public int size() {
return 0;
}
}
Tar file and untar file
Tar file stream
TarInputStream reads a UNIX tar archive as an InputStream
/*
** Authored by Timothy Gerard Endres
** <mailto:time@gjt.org> <http://www.trustice.ru>
**
** This work has been placed into the public domain.
** You may use this work in any way and for any purpose you wish.
**
** THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY OF ANY KIND,
** NOT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY. THE AUTHOR
** OF THIS SOFTWARE, ASSUMES _NO_ RESPONSIBILITY FOR ANY
** CONSEQUENCE RESULTING FROM THE USE, MODIFICATION, OR
** REDISTRIBUTION OF THIS SOFTWARE.
**
*/
import java.io.File;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
/**
* The TarInputStream reads a UNIX tar archive as an InputStream. methods are
* provided to position at each successive entry in the archive, and the read
* each entry as a normal input stream using read().
*
* @version $Revision: 12504 $
* @author Timothy Gerard Endres, .
* @see TarArchive
*/
class TarBuffer extends Object {
public static final int DEFAULT_RCDSIZE = (512);
public static final int DEFAULT_BLKSIZE = (DEFAULT_RCDSIZE * 20);
private InputStream inStream;
private OutputStream outStream;
private byte[] blockBuffer;
private int currBlkIdx;
private int currRecIdx;
private int blockSize;
private int recordSize;
private int recsPerBlock;
private boolean debug;
public TarBuffer(InputStream inStream) {
this(inStream, TarBuffer.DEFAULT_BLKSIZE);
}
public TarBuffer(InputStream inStream, int blockSize) {
this(inStream, blockSize, TarBuffer.DEFAULT_RCDSIZE);
}
public TarBuffer(InputStream inStream, int blockSize, int recordSize) {
this.inStream = inStream;
this.outStream = null;
this.initialize(blockSize, recordSize);
}
public TarBuffer(OutputStream outStream) {
this(outStream, TarBuffer.DEFAULT_BLKSIZE);
}
public TarBuffer(OutputStream outStream, int blockSize) {
this(outStream, blockSize, TarBuffer.DEFAULT_RCDSIZE);
}
public TarBuffer(OutputStream outStream, int blockSize, int recordSize) {
this.inStream = null;
this.outStream = outStream;
this.initialize(blockSize, recordSize);
}
/**
* Initialization common to all constructors.
*/
private void initialize(int blockSize, int recordSize) {
this.debug = false;
this.blockSize = blockSize;
this.recordSize = recordSize;
this.recsPerBlock = (this.blockSize / this.recordSize);
this.blockBuffer = new byte[this.blockSize];
if (this.inStream != null) {
this.currBlkIdx = -1;
this.currRecIdx = this.recsPerBlock;
} else {
this.currBlkIdx = 0;
this.currRecIdx = 0;
}
}
/**
* Get the TAR Buffer"s block size. Blocks consist of multiple records.
*/
public int getBlockSize() {
return this.blockSize;
}
/**
* Get the TAR Buffer"s record size.
*/
public int getRecordSize() {
return this.recordSize;
}
/**
* Set the debugging flag for the buffer.
*
* @param debug
* If true, print debugging output.
*/
public void setDebug(boolean debug) {
this.debug = debug;
}
/**
* Determine if an archive record indicate End of Archive. End of archive is
* indicated by a record that consists entirely of null bytes.
*
* @param record
* The record data to check.
*/
public boolean isEOFRecord(byte[] record) {
for (int i = 0, sz = this.getRecordSize(); i < sz; ++i)
if (record[i] != 0)
return false;
return true;
}
/**
* Skip over a record on the input stream.
*/
public void skipRecord() throws IOException {
if (this.debug) {
System.err
.println("SkipRecord: recIdx = " + this.currRecIdx + " blkIdx = " + this.currBlkIdx);
}
if (this.inStream == null)
throw new IOException("reading (via skip) from an output buffer");
if (this.currRecIdx >= this.recsPerBlock) {
if (!this.readBlock())
return; // UNDONE
}
this.currRecIdx++;
}
/**
* Read a record from the input stream and return the data.
*
* @return The record data.
*/
public byte[] readRecord() throws IOException {
if (this.debug) {
System.err
.println("ReadRecord: recIdx = " + this.currRecIdx + " blkIdx = " + this.currBlkIdx);
}
if (this.inStream == null)
throw new IOException("reading from an output buffer");
if (this.currRecIdx >= this.recsPerBlock) {
if (!this.readBlock())
return null;
}
byte[] result = new byte[this.recordSize];
System.arraycopy(this.blockBuffer, (this.currRecIdx * this.recordSize), result, 0,
this.recordSize);
this.currRecIdx++;
return result;
}
/**
* @return false if End-Of-File, else true
*/
private boolean readBlock() throws IOException {
if (this.debug) {
System.err.println("ReadBlock: blkIdx = " + this.currBlkIdx);
}
if (this.inStream == null)
throw new IOException("reading from an output buffer");
this.currRecIdx = 0;
int offset = 0;
int bytesNeeded = this.blockSize;
for (; bytesNeeded > 0;) {
long numBytes = this.inStream.read(this.blockBuffer, offset, bytesNeeded);
//
// NOTE
// We have fit EOF, and the block is not full!
//
// This is a broken archive. It does not follow the standard
// blocking algorithm. However, because we are generous, and
// it requires little effort, we will simply ignore the error
// and continue as if the entire block were read. This does
// not appear to break anything upstream. We used to return
// false in this case.
//
// Thanks to "Yohann.Roussel@alcatel.fr" for this fix.
//
if (numBytes == -1)
break;
offset += numBytes;
bytesNeeded -= numBytes;
if (numBytes != this.blockSize) {
if (this.debug) {
System.err.println("ReadBlock: INCOMPLETE READ " + numBytes + " of " + this.blockSize
+ " bytes read.");
}
}
}
this.currBlkIdx++;
return true;
}
/**
* Get the current block number, zero based.
*
* @return The current zero based block number.
*/
public int getCurrentBlockNum() {
return this.currBlkIdx;
}
/**
* Get the current record number, within the current block, zero based. Thus,
* current offset = (currentBlockNum * recsPerBlk) + currentRecNum.
*
* @return The current zero based record number.
*/
public int getCurrentRecordNum() {
return this.currRecIdx - 1;
}
/**
* Write an archive record to the archive.
*
* @param record
* The record data to write to the archive.
*/
public void writeRecord(byte[] record) throws IOException {
if (this.debug) {
System.err.println("WriteRecord: recIdx = " + this.currRecIdx + " blkIdx = "
+ this.currBlkIdx);
}
if (this.outStream == null)
throw new IOException("writing to an input buffer");
if (record.length != this.recordSize)
throw new IOException("record to write has length "" + record.length
+ "" which is not the record size of "" + this.recordSize + """);
if (this.currRecIdx >= this.recsPerBlock) {
this.writeBlock();
}
System.arraycopy(record, 0, this.blockBuffer, (this.currRecIdx * this.recordSize),
this.recordSize);
this.currRecIdx++;
}
/**
* Write an archive record to the archive, where the record may be inside of a
* larger array buffer. The buffer must be "offset plus record size" long.
*
* @param buf
* The buffer containing the record data to write.
* @param offset
* The offset of the record data within buf.
*/
public void writeRecord(byte[] buf, int offset) throws IOException {
if (this.debug) {
System.err.println("WriteRecord: recIdx = " + this.currRecIdx + " blkIdx = "
+ this.currBlkIdx);
}
if (this.outStream == null)
throw new IOException("writing to an input buffer");
if ((offset + this.recordSize) > buf.length)
throw new IOException("record has length "" + buf.length + "" with offset "" + offset
+ "" which is less than the record size of "" + this.recordSize + """);
if (this.currRecIdx >= this.recsPerBlock) {
this.writeBlock();
}
System.arraycopy(buf, offset, this.blockBuffer, (this.currRecIdx * this.recordSize),
this.recordSize);
this.currRecIdx++;
}
/**
* Write a TarBuffer block to the archive.
*/
private void writeBlock() throws IOException {
if (this.debug) {
System.err.println("WriteBlock: blkIdx = " + this.currBlkIdx);
}
if (this.outStream == null)
throw new IOException("writing to an input buffer");
this.outStream.write(this.blockBuffer, 0, this.blockSize);
this.outStream.flush();
this.currRecIdx = 0;
this.currBlkIdx++;
}
/**
* Flush the current data block if it has any data in it.
*/
private void flushBlock() throws IOException {
if (this.debug) {
System.err.println("TarBuffer.flushBlock() called.");
}
if (this.outStream == null)
throw new IOException("writing to an input buffer");
if (this.currRecIdx > 0) {
this.writeBlock();
}
}
/**
* Close the TarBuffer. If this is an output buffer, also flush the current
* block before closing.
*/
public void close() throws IOException {
if (this.debug) {
System.err.println("TarBuffer.closeBuffer().");
}
if (this.outStream != null) {
this.flushBlock();
if (this.outStream != System.out && this.outStream != System.err) {
this.outStream.close();
this.outStream = null;
}
} else if (this.inStream != null) {
if (this.inStream != System.in) {
this.inStream.close();
this.inStream = null;
}
}
}
}
class InvalidHeaderException extends IOException {
public InvalidHeaderException() {
super();
}
public InvalidHeaderException(String msg) {
super(msg);
}
}
TarOutputStream writes a UNIX tar archive as an OutputStream
/*
** Authored by Timothy Gerard Endres
** <mailto:time@gjt.org> <http://www.trustice.ru>
**
** This work has been placed into the public domain.
** You may use this work in any way and for any purpose you wish.
**
** THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY OF ANY KIND,
** NOT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY. THE AUTHOR
** OF THIS SOFTWARE, ASSUMES _NO_ RESPONSIBILITY FOR ANY
** CONSEQUENCE RESULTING FROM THE USE, MODIFICATION, OR
** REDISTRIBUTION OF THIS SOFTWARE.
**
*/
import java.io.File;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
/**
* The TarOutputStream writes a UNIX tar archive as an OutputStream.
* Methods are provided to put entries, and then write their contents
* by writing to this stream using write().
*
*
* @version $Revision: 12504 $
* @author Timothy Gerard Endres,
* .
* @see TarArchive
*/
class TarBuffer extends Object {
public static final int DEFAULT_RCDSIZE = (512);
public static final int DEFAULT_BLKSIZE = (DEFAULT_RCDSIZE * 20);
private InputStream inStream;
private OutputStream outStream;
private byte[] blockBuffer;
private int currBlkIdx;
private int currRecIdx;
private int blockSize;
private int recordSize;
private int recsPerBlock;
private boolean debug;
public TarBuffer(InputStream inStream) {
this(inStream, TarBuffer.DEFAULT_BLKSIZE);
}
public TarBuffer(InputStream inStream, int blockSize) {
this(inStream, blockSize, TarBuffer.DEFAULT_RCDSIZE);
}
public TarBuffer(InputStream inStream, int blockSize, int recordSize) {
this.inStream = inStream;
this.outStream = null;
this.initialize(blockSize, recordSize);
}
public TarBuffer(OutputStream outStream) {
this(outStream, TarBuffer.DEFAULT_BLKSIZE);
}
public TarBuffer(OutputStream outStream, int blockSize) {
this(outStream, blockSize, TarBuffer.DEFAULT_RCDSIZE);
}
public TarBuffer(OutputStream outStream, int blockSize, int recordSize) {
this.inStream = null;
this.outStream = outStream;
this.initialize(blockSize, recordSize);
}
/**
* Initialization common to all constructors.
*/
private void initialize(int blockSize, int recordSize) {
this.debug = false;
this.blockSize = blockSize;
this.recordSize = recordSize;
this.recsPerBlock = (this.blockSize / this.recordSize);
this.blockBuffer = new byte[this.blockSize];
if (this.inStream != null) {
this.currBlkIdx = -1;
this.currRecIdx = this.recsPerBlock;
} else {
this.currBlkIdx = 0;
this.currRecIdx = 0;
}
}
/**
* Get the TAR Buffer"s block size. Blocks consist of multiple records.
*/
public int getBlockSize() {
return this.blockSize;
}
/**
* Get the TAR Buffer"s record size.
*/
public int getRecordSize() {
return this.recordSize;
}
/**
* Set the debugging flag for the buffer.
*
* @param debug
* If true, print debugging output.
*/
public void setDebug(boolean debug) {
this.debug = debug;
}
/**
* Determine if an archive record indicate End of Archive. End of archive is
* indicated by a record that consists entirely of null bytes.
*
* @param record
* The record data to check.
*/
public boolean isEOFRecord(byte[] record) {
for (int i = 0, sz = this.getRecordSize(); i < sz; ++i)
if (record[i] != 0)
return false;
return true;
}
/**
* Skip over a record on the input stream.
*/
public void skipRecord() throws IOException {
if (this.debug) {
System.err
.println("SkipRecord: recIdx = " + this.currRecIdx + " blkIdx = " + this.currBlkIdx);
}
if (this.inStream == null)
throw new IOException("reading (via skip) from an output buffer");
if (this.currRecIdx >= this.recsPerBlock) {
if (!this.readBlock())
return; // UNDONE
}
this.currRecIdx++;
}
/**
* Read a record from the input stream and return the data.
*
* @return The record data.
*/
public byte[] readRecord() throws IOException {
if (this.debug) {
System.err
.println("ReadRecord: recIdx = " + this.currRecIdx + " blkIdx = " + this.currBlkIdx);
}
if (this.inStream == null)
throw new IOException("reading from an output buffer");
if (this.currRecIdx >= this.recsPerBlock) {
if (!this.readBlock())
return null;
}
byte[] result = new byte[this.recordSize];
System.arraycopy(this.blockBuffer, (this.currRecIdx * this.recordSize), result, 0,
this.recordSize);
this.currRecIdx++;
return result;
}
/**
* @return false if End-Of-File, else true
*/
private boolean readBlock() throws IOException {
if (this.debug) {
System.err.println("ReadBlock: blkIdx = " + this.currBlkIdx);
}
if (this.inStream == null)
throw new IOException("reading from an output buffer");
this.currRecIdx = 0;
int offset = 0;
int bytesNeeded = this.blockSize;
for (; bytesNeeded > 0;) {
long numBytes = this.inStream.read(this.blockBuffer, offset, bytesNeeded);
//
// NOTE
// We have fit EOF, and the block is not full!
//
// This is a broken archive. It does not follow the standard
// blocking algorithm. However, because we are generous, and
// it requires little effort, we will simply ignore the error
// and continue as if the entire block were read. This does
// not appear to break anything upstream. We used to return
// false in this case.
//
// Thanks to "Yohann.Roussel@alcatel.fr" for this fix.
//
if (numBytes == -1)
break;
offset += numBytes;
bytesNeeded -= numBytes;
if (numBytes != this.blockSize) {
if (this.debug) {
System.err.println("ReadBlock: INCOMPLETE READ " + numBytes + " of " + this.blockSize
+ " bytes read.");
}
}
}
this.currBlkIdx++;
return true;
}
/**
* Get the current block number, zero based.
*
* @return The current zero based block number.
*/
public int getCurrentBlockNum() {
return this.currBlkIdx;
}
/**
* Get the current record number, within the current block, zero based. Thus,
* current offset = (currentBlockNum * recsPerBlk) + currentRecNum.
*
* @return The current zero based record number.
*/
public int getCurrentRecordNum() {
return this.currRecIdx - 1;
}
/**
* Write an archive record to the archive.
*
* @param record
* The record data to write to the archive.
*/
public void writeRecord(byte[] record) throws IOException {
if (this.debug) {
System.err.println("WriteRecord: recIdx = " + this.currRecIdx + " blkIdx = "
+ this.currBlkIdx);
}
if (this.outStream == null)
throw new IOException("writing to an input buffer");
if (record.length != this.recordSize)
throw new IOException("record to write has length "" + record.length
+ "" which is not the record size of "" + this.recordSize + """);
if (this.currRecIdx >= this.recsPerBlock) {
this.writeBlock();
}
System.arraycopy(record, 0, this.blockBuffer, (this.currRecIdx * this.recordSize),
this.recordSize);
this.currRecIdx++;
}
/**
* Write an archive record to the archive, where the record may be inside of a
* larger array buffer. The buffer must be "offset plus record size" long.
*
* @param buf
* The buffer containing the record data to write.
* @param offset
* The offset of the record data within buf.
*/
public void writeRecord(byte[] buf, int offset) throws IOException {
if (this.debug) {
System.err.println("WriteRecord: recIdx = " + this.currRecIdx + " blkIdx = "
+ this.currBlkIdx);
}
if (this.outStream == null)
throw new IOException("writing to an input buffer");
if ((offset + this.recordSize) > buf.length)
throw new IOException("record has length "" + buf.length + "" with offset "" + offset
+ "" which is less than the record size of "" + this.recordSize + """);
if (this.currRecIdx >= this.recsPerBlock) {
this.writeBlock();
}
System.arraycopy(buf, offset, this.blockBuffer, (this.currRecIdx * this.recordSize),
this.recordSize);
this.currRecIdx++;
}
/**
* Write a TarBuffer block to the archive.
*/
private void writeBlock() throws IOException {
if (this.debug) {
System.err.println("WriteBlock: blkIdx = " + this.currBlkIdx);
}
if (this.outStream == null)
throw new IOException("writing to an input buffer");
this.outStream.write(this.blockBuffer, 0, this.blockSize);
this.outStream.flush();
this.currRecIdx = 0;
this.currBlkIdx++;
}
/**
* Flush the current data block if it has any data in it.
*/
private void flushBlock() throws IOException {
if (this.debug) {
System.err.println("TarBuffer.flushBlock() called.");
}
if (this.outStream == null)
throw new IOException("writing to an input buffer");
if (this.currRecIdx > 0) {
this.writeBlock();
}
}
/**
* Close the TarBuffer. If this is an output buffer, also flush the current
* block before closing.
*/
public void close() throws IOException {
if (this.debug) {
System.err.println("TarBuffer.closeBuffer().");
}
if (this.outStream != null) {
this.flushBlock();
if (this.outStream != System.out && this.outStream != System.err) {
this.outStream.close();
this.outStream = null;
}
} else if (this.inStream != null) {
if (this.inStream != System.in) {
this.inStream.close();
this.inStream = null;
}
}
}
}
class InvalidHeaderException extends IOException {
public InvalidHeaderException() {
super();
}
public InvalidHeaderException(String msg) {
super(msg);
}
}
The java.util.zip package can be used to create a checksum.
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.util.Arrays;
import java.util.zip.CRC32;
public class Main {
public static void main(String[] args) throws Exception{
BufferedInputStream is = new BufferedInputStream(new FileInputStream("a.exe"));
byte[] bytes = new byte[1024];
int len = 0;
while ((len = is.read(bytes)) >= 0) {
new CRC32().update(bytes, 0, len);
}
is.close();
System.out.println(Arrays.toString(bytes));
}
}
Unpack an archive from a URL
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class Utils {
/**
* Unpack an archive from a URL
*
* @param url
* @param targetDir
* @return the file to the url
* @throws IOException
*/
public static File unpackArchive(URL url, File targetDir) throws IOException {
if (!targetDir.exists()) {
targetDir.mkdirs();
}
InputStream in = new BufferedInputStream(url.openStream(), 1024);
// make sure we get the actual file
File zip = File.createTempFile("arc", ".zip", targetDir);
OutputStream out = new BufferedOutputStream(new FileOutputStream(zip));
copyInputStream(in, out);
out.close();
return unpackArchive(zip, targetDir);
}
/**
* Unpack a zip file
*
* @param theFile
* @param targetDir
* @return the file
* @throws IOException
*/
public static File unpackArchive(File theFile, File targetDir) throws IOException {
if (!theFile.exists()) {
throw new IOException(theFile.getAbsolutePath() + " does not exist");
}
if (!buildDirectory(targetDir)) {
throw new IOException("Could not create directory: " + targetDir);
}
ZipFile zipFile = new ZipFile(theFile);
for (Enumeration entries = zipFile.entries(); entries.hasMoreElements();) {
ZipEntry entry = (ZipEntry) entries.nextElement();
File file = new File(targetDir, File.separator + entry.getName());
if (!buildDirectory(file.getParentFile())) {
throw new IOException("Could not create directory: " + file.getParentFile());
}
if (!entry.isDirectory()) {
copyInputStream(zipFile.getInputStream(entry), new BufferedOutputStream(new FileOutputStream(file)));
} else {
if (!buildDirectory(file)) {
throw new IOException("Could not create directory: " + file);
}
}
}
zipFile.close();
return theFile;
}
public static void copyInputStream(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int len = in.read(buffer);
while (len >= 0) {
out.write(buffer, 0, len);
len = in.read(buffer);
}
in.close();
out.close();
}
public static boolean buildDirectory(File file) {
return file.exists() || file.mkdirs();
}
}
Unpack a segment from a zip
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class Utils {
/**
* unpack a segment from a zip
*
* @param addsi
* @param packetStream
* @param version
*/
public static void unpack(InputStream source, File destination) throws IOException {
ZipInputStream zin = new ZipInputStream(source);
ZipEntry zipEntry = null;
FileOutputStream fout = null;
byte[] buffer = new byte[4096];
while ((zipEntry = zin.getNextEntry()) != null) {
long ts = zipEntry.getTime();
// the zip entry needs to be a full path from the
// searchIndexDirectory... hence this is correct
File f = new File(destination, zipEntry.getName());
f.getParentFile().mkdirs();
fout = new FileOutputStream(f);
int len;
while ((len = zin.read(buffer)) > 0) {
fout.write(buffer, 0, len);
}
zin.closeEntry();
fout.close();
f.setLastModified(ts);
}
fout.close();
}
}
Unpack a zip file
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class Utils {
/**
* Unpack a zip file
*
* @param theFile
* @param targetDir
* @return the file
* @throws IOException
*/
public static File unpackArchive(File theFile, File targetDir) throws IOException {
if (!theFile.exists()) {
throw new IOException(theFile.getAbsolutePath() + " does not exist");
}
if (!buildDirectory(targetDir)) {
throw new IOException("Could not create directory: " + targetDir);
}
ZipFile zipFile = new ZipFile(theFile);
for (Enumeration entries = zipFile.entries(); entries.hasMoreElements();) {
ZipEntry entry = (ZipEntry) entries.nextElement();
File file = new File(targetDir, File.separator + entry.getName());
if (!buildDirectory(file.getParentFile())) {
throw new IOException("Could not create directory: " + file.getParentFile());
}
if (!entry.isDirectory()) {
copyInputStream(zipFile.getInputStream(entry), new BufferedOutputStream(new FileOutputStream(file)));
} else {
if (!buildDirectory(file)) {
throw new IOException("Could not create directory: " + file);
}
}
}
zipFile.close();
return theFile;
}
public static void copyInputStream(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int len = in.read(buffer);
while (len >= 0) {
out.write(buffer, 0, len);
len = in.read(buffer);
}
in.close();
out.close();
}
public static boolean buildDirectory(File file) {
return file.exists() || file.mkdirs();
}
}
Unzip file to a directory
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class Utils {
public static void unzip(File srcFile, File destDir) throws IOException {
InputStream input = null;
OutputStream output = null;
ZipFile zipfile = new ZipFile(srcFile);
Enumeration zipEntries = zipfile.entries();
while (zipEntries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) zipEntries.nextElement();
if (entry.isDirectory()) {
new File(destDir, entry.getName()).mkdir();
continue;
}
input = new BufferedInputStream(zipfile.getInputStream(entry));
File destFile = new File(destDir, entry.getName());
FileOutputStream fos = new FileOutputStream(destFile);
output = new BufferedOutputStream(fos);
copyStreams(input, output);
input.close();
output.flush();
output.close();
}
}
private static void copyStreams(InputStream input, OutputStream output) throws IOException {
int count;
byte data[] = new byte[1024];
while ((count = input.read(data, 0, 1024)) != -1) {
output.write(data, 0, count);
}
}
}
UnZip -- print or unzip a JAR or PKZIP file using java.util.zip
/*
* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS""
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java
* language and environment is gratefully acknowledged.
*
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
* UnZip -- print or unzip a JAR or PKZIP file using java.util.zip. Command-line
* version: extracts files.
*
* @author Ian Darwin, Ian@DarwinSys.ru $Id: UnZip.java,v 1.7 2004/03/07
* 17:40:35 ian Exp $
*/
public class UnZip {
/** Constants for mode listing or mode extracting. */
public static final int LIST = 0, EXTRACT = 1;
/** Whether we are extracting or just printing TOC */
protected int mode = LIST;
/** The ZipFile that is used to read an archive */
protected ZipFile zippy;
/** The buffer for reading/writing the ZipFile data */
protected byte[] b;
/**
* Simple main program, construct an UnZipper, process each .ZIP file from
* argv[] through that object.
*/
public static void main(String[] argv) {
UnZip u = new UnZip();
for (int i = 0; i < argv.length; i++) {
if ("-x".equals(argv[i])) {
u.setMode(EXTRACT);
continue;
}
String candidate = argv[i];
// System.err.println("Trying path " + candidate);
if (candidate.endsWith(".zip") || candidate.endsWith(".jar"))
u.unZip(candidate);
else
System.err.println("Not a zip file? " + candidate);
}
System.err.println("All done!");
}
/** Construct an UnZip object. Just allocate the buffer */
UnZip() {
b = new byte[8092];
}
/** Set the Mode (list, extract). */
protected void setMode(int m) {
if (m == LIST || m == EXTRACT)
mode = m;
}
/** Cache of paths we"ve mkdir()ed. */
protected SortedSet dirsMade;
/** For a given Zip file, process each entry. */
public void unZip(String fileName) {
dirsMade = new TreeSet();
try {
zippy = new ZipFile(fileName);
Enumeration all = zippy.entries();
while (all.hasMoreElements()) {
getFile((ZipEntry) all.nextElement());
}
} catch (IOException err) {
System.err.println("IO Error: " + err);
return;
}
}
protected boolean warnedMkDir = false;
/**
* Process one file from the zip, given its name. Either print the name, or
* create the file on disk.
*/
protected void getFile(ZipEntry e) throws IOException {
String zipName = e.getName();
switch (mode) {
case EXTRACT:
if (zipName.startsWith("/")) {
if (!warnedMkDir)
System.out.println("Ignoring absolute paths");
warnedMkDir = true;
zipName = zipName.substring(1);
}
// if a directory, just return. We mkdir for every file,
// since some widely-used Zip creators don"t put out
// any directory entries, or put them in the wrong place.
if (zipName.endsWith("/")) {
return;
}
// Else must be a file; open the file for output
// Get the directory part.
int ix = zipName.lastIndexOf("/");
if (ix > 0) {
String dirName = zipName.substring(0, ix);
if (!dirsMade.contains(dirName)) {
File d = new File(dirName);
// If it already exists as a dir, don"t do anything
if (!(d.exists() && d.isDirectory())) {
// Try to create the directory, warn if it fails
System.out.println("Creating Directory: " + dirName);
if (!d.mkdirs()) {
System.err.println("Warning: unable to mkdir "
+ dirName);
}
dirsMade.add(dirName);
}
}
}
System.err.println("Creating " + zipName);
FileOutputStream os = new FileOutputStream(zipName);
InputStream is = zippy.getInputStream(e);
int n = 0;
while ((n = is.read(b)) > 0)
os.write(b, 0, n);
is.close();
os.close();
break;
case LIST:
// Not extracting, just list
if (e.isDirectory()) {
System.out.println("Directory " + zipName);
} else {
System.out.println("File " + zipName);
}
break;
default:
throw new IllegalStateException("mode value (" + mode + ") bad");
}
}
}
Unzipps a zip file placed at zipURL to path
/**
* Copyright (c) 2003 Daffodil Software Ltd all rights reserved.
* This program is free software; you can redistribute it and/or modify
* it under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
* There are special exceptions to the terms and conditions of the GPL
* as it is applied to this software. See the GNU General Public License for more details.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
import java.io.*;
import java.util.zip.*;
/**
* This class is used to make zip file of the XML file,BLOB.lob and CLOB.lob
* so that compacted files can be transferred over the network. Besides it, this
* class contains method for unzipping it.
*/
public class ZipHandler
{
/**
* makes a zip file named <xmlFileName> from <xmlURL> at path <zipURL>
* @param zipURL
* @param xmlURL
* @param xmlFileName
*/
public static void makeZip(String zipURL, String xmlURL, String xmlFileName) throws
IOException
{
FileOutputStream fos = new FileOutputStream(new File(zipURL));
ZipOutputStream zos = new ZipOutputStream(fos);
// zos.setLevel();
FileInputStream fis = new FileInputStream(xmlURL);
zos.putNextEntry(new ZipEntry(xmlFileName+".xml"));
writeInOutputStream(fis,zos);
String bpath = "c:\\";
FileInputStream fisBLOB = createInputStream(bpath);
zos.putNextEntry(new ZipEntry("blob.lob"));
writeInOutputStream(fisBLOB, zos);
zos.closeEntry();
String cpath = "c:\\";
FileInputStream fisCLOB = createInputStream(cpath);
zos.putNextEntry(new ZipEntry("clob.lob"));
writeInOutputStream(fisCLOB, zos);
zos.closeEntry();
fis.close();
fisCLOB.close();
fisBLOB.close();
zos.close();
fos.close();
}
/**
* unzipps a zip file placed at <zipURL> to path <xmlURL>
* @param zipURL
* @param xmlURL
*/
public static void unZip(String zipURL, String xmlURL) throws IOException
{
FileOutputStream fosBLOB = new FileOutputStream(new File("c:\\"));
FileOutputStream fosCLOB = new FileOutputStream(new File("c:\\"));
FileInputStream fis = new FileInputStream(new File(zipURL));
ZipInputStream zis = new ZipInputStream(fis);
FileOutputStream fos = new FileOutputStream(xmlURL);
ZipEntry ze = zis.getNextEntry();
ExtractZip(zis, fos, fosBLOB, fosCLOB, ze);
ze = zis.getNextEntry();
ExtractZip(zis, fos, fosBLOB, fosCLOB, ze);
ze = zis.getNextEntry();
ExtractZip(zis, fos, fosBLOB, fosCLOB, ze);
fos.flush();
fis.close();
fos.close();
fosCLOB.close();
fosBLOB.close();
zis.close();
}
private static void ExtractZip(ZipInputStream zis, FileOutputStream fos,
FileOutputStream fosBLOB,
FileOutputStream fosCLOB, ZipEntry ze) throws
IOException {
if (ze.getName().equalsIgnoreCase("blob.lob"))
writeInOutputStream(zis, fosBLOB);
else if (ze.getName().equalsIgnoreCase("clob.lob"))
writeInOutputStream(zis, fosCLOB);
else
writeInOutputStream(zis, fos);
}
private static void writeInOutputStream(InputStream is,
OutputStream os) throws
IOException {
byte[] buf = new byte[1024];
int len = 0;
while ( (len = is.read(buf)) > 0)
{
os.write(buf, 0, len);
}
}
/**
* makes a zip file named <xmlFileName> from <xmlURL> at path <zipURL>
* @param zipURL
* @param xmlURL
* @param xmlFileName
*/
public static void makeStructZip(String zipURL, String xmlURL, String xmlFileName) throws
IOException
{
FileOutputStream fos = new FileOutputStream(new File(zipURL));
ZipOutputStream zos = new ZipOutputStream(fos);
// zos.setLevel();
FileInputStream fis = new FileInputStream(xmlURL);
zos.putNextEntry(new ZipEntry(xmlFileName+".xml"));
writeInOutputStream(fis,zos);
zos.closeEntry();
fis.close();
zos.close();
}
/**
* unzipps a zip file placed at <zipURL> to path <xmlURL>
* @param zipURL
* @param xmlURL
*/
public static void unStructZip(String zipURL, String xmlURL) throws IOException
{
FileInputStream fis = new FileInputStream(new File(zipURL));
ZipInputStream zis = new ZipInputStream(fis);
FileOutputStream fos = new FileOutputStream(xmlURL);
ZipEntry ze = zis.getNextEntry();
writeInOutputStream(zis,fos);
fos.flush();
fis.close();
fos.close();
zis.close();
}
private static FileInputStream createInputStream(String bpath) throws IOException{
FileInputStream fis = null;
try
{
fis = new FileInputStream(bpath);
}
catch (FileNotFoundException ex)
{
FileOutputStream temp = new FileOutputStream(bpath);
fis = new FileInputStream(bpath);
}
return fis;
}
}
Use Java code to zip a folder
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class FolderZiper {
public static void main(String[] a) throws Exception {
zipFolder("c:\\a", "c:\\a.zip");
}
static public void zipFolder(String srcFolder, String destZipFile) throws Exception {
ZipOutputStream zip = null;
FileOutputStream fileWriter = null;
fileWriter = new FileOutputStream(destZipFile);
zip = new ZipOutputStream(fileWriter);
addFolderToZip("", srcFolder, zip);
zip.flush();
zip.close();
}
static private void addFileToZip(String path, String srcFile, ZipOutputStream zip)
throws Exception {
File folder = new File(srcFile);
if (folder.isDirectory()) {
addFolderToZip(path, srcFile, zip);
} else {
byte[] buf = new byte[1024];
int len;
FileInputStream in = new FileInputStream(srcFile);
zip.putNextEntry(new ZipEntry(path + "/" + folder.getName()));
while ((len = in.read(buf)) > 0) {
zip.write(buf, 0, len);
}
}
}
static private void addFolderToZip(String path, String srcFolder, ZipOutputStream zip)
throws Exception {
File folder = new File(srcFolder);
for (String fileName : folder.list()) {
if (path.equals("")) {
addFileToZip(folder.getName(), srcFolder + "/" + fileName, zip);
} else {
addFileToZip(path + "/" + folder.getName(), srcFolder + "/" + fileName, zip);
}
}
}
}
Uses Zip compression to compress any number of files given on the command line
// : c12:ZipCompress.java
// Uses Zip compression to compress any
// number of files given on the command line.
// {Args: ZipCompress.java}
// {Clean: test.zip}
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.Adler32;
import java.util.zip.CheckedInputStream;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
public class ZipCompress {
// Throw exceptions to console:
public static void main(String[] args) throws IOException {
FileOutputStream f = new FileOutputStream("test.zip");
CheckedOutputStream csum = new CheckedOutputStream(f, new Adler32());
ZipOutputStream zos = new ZipOutputStream(csum);
BufferedOutputStream out = new BufferedOutputStream(zos);
zos.setComment("A test of Java Zipping");
// No corresponding getComment(), though.
for (int i = 0; i < args.length; i++) {
System.out.println("Writing file " + args[i]);
BufferedReader in = new BufferedReader(new FileReader(args[i]));
zos.putNextEntry(new ZipEntry(args[i]));
int c;
while ((c = in.read()) != -1)
out.write(c);
in.close();
}
out.close();
// Checksum valid only after the file has been closed!
System.out.println("Checksum: " + csum.getChecksum().getValue());
// Now extract the files:
System.out.println("Reading file");
FileInputStream fi = new FileInputStream("test.zip");
CheckedInputStream csumi = new CheckedInputStream(fi, new Adler32());
ZipInputStream in2 = new ZipInputStream(csumi);
BufferedInputStream bis = new BufferedInputStream(in2);
ZipEntry ze;
while ((ze = in2.getNextEntry()) != null) {
System.out.println("Reading file " + ze);
int x;
while ((x = bis.read()) != -1)
System.out.write(x);
}
System.out.println("Checksum: " + csumi.getChecksum().getValue());
bis.close();
// Alternative way to open and read zip files:
ZipFile zf = new ZipFile("test.zip");
Enumeration e = zf.entries();
while (e.hasMoreElements()) {
ZipEntry ze2 = (ZipEntry) e.nextElement();
System.out.println("File: " + ze2);
// ... and extract the data as before
}
}
} ///:~
Validate that an archive contains a named entry
import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class Utils {
/**
* Validate that an archive contains a named entry
*
* @param theFile
* @param name
* @return true if the entry exists
* @throws IOException
*/
public static boolean archiveContainsEntry(File theFile, String name) throws IOException {
boolean result = false;
ZipFile zipFile;
zipFile = new ZipFile(theFile);
for (Enumeration entries = zipFile.entries(); entries.hasMoreElements();) {
ZipEntry entry = (ZipEntry) entries.nextElement();
if (entry.getName().equals(name)) {
result = true;
break;
}
}
zipFile.close();
return result;
}
}
Write Zip file
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class Main {
public static void main(String[] args) throws Exception {
FileOutputStream fos = new FileOutputStream("C:/MyZip.zip");
ZipOutputStream zos = new ZipOutputStream(fos);
ZipEntry ze = new ZipEntry("C:/file1.txt");
zos.putNextEntry(ze);
zos.closeEntry();
ze = new ZipEntry("C:/file2.txt");
zos.putNextEntry(ze);
zos.closeEntry();
zos.close();
}
}
Zip a list of file into one zip file.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class Utils {
/**
* Zip a list of file into one zip file.
*
* @param files
* files to zip
* @param targetZipFile
* target zip file
* @throws IOException
* IO error exception can be thrown when copying ...
*/
public static void zipFile(final File[] files, final File targetZipFile) throws IOException {
try {
FileOutputStream fos = new FileOutputStream(targetZipFile);
ZipOutputStream zos = new ZipOutputStream(fos);
byte[] buffer = new byte[128];
for (int i = 0; i < files.length; i++) {
File currentFile = files[i];
if (!currentFile.isDirectory()) {
ZipEntry entry = new ZipEntry(currentFile.getName());
FileInputStream fis = new FileInputStream(currentFile);
zos.putNextEntry(entry);
int read = 0;
while ((read = fis.read(buffer)) != -1) {
zos.write(buffer, 0, read);
}
zos.closeEntry();
fis.close();
}
}
zos.close();
fos.close();
} catch (FileNotFoundException e) {
System.out.println("File not found : " + e);
}
}
}
Zip Compare
/* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.util.zip.ZipFile;
import java.util.zip.ZipEntry;
import java.util.*;
import java.io.IOException;
import java.io.InputStream;
public class ZipCompare
{
public static void main(String[] args)
{
if (args.length != 2)
{
System.out.println("Usage: zipcompare [file1] [file2]");
System.exit(1);
}
ZipFile file1;
try { file1 = new ZipFile(args[0]); }
catch (IOException e) { System.out.println("Could not open zip file " + args[0] + ": " + e); System.exit(1); return; }
ZipFile file2;
try { file2 = new ZipFile(args[1]); }
catch (IOException e) { System.out.println("Could not open zip file " + args[0] + ": " + e); System.exit(1); return; }
System.out.println("Comparing " + args[0] + " with " + args[1] + ":");
Set set1 = new LinkedHashSet();
for (Enumeration e = file1.entries(); e.hasMoreElements(); )
set1.add(((ZipEntry)e.nextElement()).getName());
Set set2 = new LinkedHashSet();
for (Enumeration e = file2.entries(); e.hasMoreElements(); )
set2.add(((ZipEntry)e.nextElement()).getName());
int errcount = 0;
int filecount = 0;
for (Iterator i = set1.iterator(); i.hasNext(); )
{
String name = (String)i.next();
if (!set2.contains(name))
{
System.out.println(name + " not found in " + args[1]);
errcount += 1;
continue;
}
try
{
set2.remove(name);
if (!streamsEqual(file1.getInputStream(file1.getEntry(name)), file2.getInputStream(file2.getEntry(name))))
{
System.out.println(name + " does not match");
errcount += 1;
continue;
}
}
catch (Exception e)
{
System.out.println(name + ": IO Error " + e);
e.printStackTrace();
errcount += 1;
continue;
}
filecount += 1;
}
for (Iterator i = set2.iterator(); i.hasNext(); )
{
String name = (String)i.next();
System.out.println(name + " not found in " + args[0]);
errcount += 1;
}
System.out.println(filecount + " entries matched");
if (errcount > 0)
{
System.out.println(errcount + " entries did not match");
System.exit(1);
}
System.exit(0);
}
static boolean streamsEqual(InputStream stream1, InputStream stream2) throws IOException
{
byte[] buf1 = new byte[4096];
byte[] buf2 = new byte[4096];
boolean done1 = false;
boolean done2 = false;
try
{
while (!done1)
{
int off1 = 0;
int off2 = 0;
while (off1 < buf1.length)
{
int count = stream1.read(buf1, off1, buf1.length - off1);
if (count < 0)
{
done1 = true;
break;
}
off1 += count;
}
while (off2 < buf2.length)
{
int count = stream2.read(buf2, off2, buf2.length - off2);
if (count < 0)
{
done2 = true;
break;
}
off2 += count;
}
if (off1 != off2 || done1 != done2)
return false;
for (int i = 0; i < off1; i++)
{
if (buf1[i] != buf2[i])
return false;
}
}
return true;
}
finally { stream1.close(); stream2.close(); }
}
}
Zip unzip byte array
/*
* Copyright (C) 2001, 2002 Robert MacGrogan
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*
* $Archive: SourceJammer$
* $FileName: ZipUtil.java$
* $FileID: 4327$
*
* Last change:
* $AuthorName: Rob MacGrogan$
* $Date: 4/23/03 5:23 PM$
* $Comment: Replaced GPL header with LGPL header.$
*
* $KeyWordsOff: $
*/
/**
* Title: SourceJammer Library 1.0
* Description:
* Copyright: Copyright (c) 2001
* Company: SourceJammer Project
* @author Robert MacGrogan
* @version 1.0
*/
import java.util.HashMap;
import java.util.zip.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.*;
/**
* Static utility methods for zipping data.
*/
public class ZipUtil {
public static final int ZIP_BUFFER_SIZE = 50;
private static final int STREAM_BUFFER_SIZE = 1024;
private ZipUtil() {
}
/**
* Deflates the file and returns the deflated file.
*/
public static byte[] zipByteArray(byte[] file)
throws IOException{
byte[] byReturn = null;
Deflater oDeflate = new Deflater(Deflater.DEFLATED, false);
oDeflate.setInput(file);
oDeflate.finish();
ByteArrayOutputStream oZipStream = new ByteArrayOutputStream();
try {
while (! oDeflate.finished() ){
byte[] byRead = new byte[ZIP_BUFFER_SIZE];
int iBytesRead = oDeflate.deflate(byRead);
if (iBytesRead == byRead.length){
oZipStream.write(byRead);
}
else {
oZipStream.write(byRead, 0, iBytesRead);
}
}
oDeflate.end();
byReturn = oZipStream.toByteArray();
}
finally {
oZipStream.close();
}
return byReturn;
}
/**
* Inflates a previously deflated file.
*/
public static byte[] unzipByteArray(byte[] file)
throws IOException {
byte[] byReturn = null;
Inflater oInflate = new Inflater(false);
oInflate.setInput(file);
ByteArrayOutputStream oZipStream = new ByteArrayOutputStream();
try {
while (! oInflate.finished() ){
byte[] byRead = new byte[ZIP_BUFFER_SIZE];
int iBytesRead = oInflate.inflate(byRead);
if (iBytesRead == byRead.length){
oZipStream.write(byRead);
}
else {
oZipStream.write(byRead, 0, iBytesRead);
}
}
byReturn = oZipStream.toByteArray();
}
catch (DataFormatException ex){
throw new IOException("Attempting to unzip file that is not zipped.");
}
finally {
oZipStream.close();
}
return byReturn;
}
/*
public static void zipFileToFile(File flSource, File flTarget)
throws IOException{
Deflater oDeflate = new Deflater(Deflater.DEFLATED, false);
FileInputStream stmFileIn = new FileInputStream(flSource);
FileOutputStream stmFileOut = new FileOutputStream(flTarget);
DeflaterOutputStream stmDeflateOut = new DeflaterOutputStream(stmFileOut, oDeflate);
byte[] buffer = null;
int iBufferSize = STREAM_BUFFER_SIZE;
boolean bKeepZipping = true;
try{
while (bKeepZipping){
buffer = new byte[iBufferSize];
int iBytes = stmFileIn.read(buffer);
if (iBytes == -1){
bKeepZipping = false;
}
else{
if (iBytes < iBufferSize){
bKeepZipping = false;
byte[] tmp = new byte[iBytes];
for (int i = 0; i < iBytes; i++){
tmp[i] = buffer[i];
}
buffer = tmp;
}
stmDeflateOut.write(buffer);
}//end else some bytes returned.
}//end while
}//end try
finally{
stmDeflateOut.finish();
stmDeflateOut.flush();
stmDeflateOut.close();
stmFileOut.close();
stmFileIn.close();
}
}
*/
public static void zipFileToFile(File flSource, File flTarget)
throws IOException{
Deflater oDeflate = new Deflater(Deflater.DEFLATED, false);
FileInputStream stmFileIn = new FileInputStream(flSource);
FileOutputStream stmFileOut = new FileOutputStream(flTarget);
DeflaterOutputStream stmDeflateOut = new DeflaterOutputStream(stmFileOut, oDeflate);
try{
// FileUtil.inputStreamToOutputStream(stmFileIn, stmDeflateOut);
}//end try
finally{
stmDeflateOut.finish();
stmDeflateOut.flush();
stmDeflateOut.close();
stmFileOut.close();
stmFileIn.close();
}
}
public static void unzipFileToFile(File flSource, File flTarget)
throws IOException{
Inflater oInflate = new Inflater(false);
FileInputStream stmFileIn = new FileInputStream(flSource);
FileOutputStream stmFileOut = new FileOutputStream(flTarget);
InflaterInputStream stmInflateIn = new InflaterInputStream(stmFileIn, oInflate);
try{
inflaterInputStmToFileOutputStm(stmInflateIn, stmFileOut);
}//end try
finally{
stmFileOut.flush();
stmFileOut.close();
stmInflateIn.close();
stmFileIn.close();
}
}
private static void inflaterInputStmToFileOutputStm(InflaterInputStream stmIn,
FileOutputStream stmOut)
throws IOException{
byte[] buffer = null;
int iBufferSize = STREAM_BUFFER_SIZE;
boolean bKeepStreaming = true;
while (bKeepStreaming){
buffer = new byte[iBufferSize];
int iBytes = stmIn.read(buffer);
if (iBytes == -1){
bKeepStreaming = false;
}
else{
if (iBytes < iBufferSize){
bKeepStreaming = false;
byte[] tmp = new byte[iBytes];
for (int i = 0; i < iBytes; i++){
tmp[i] = buffer[i];
}
buffer = tmp;
}
stmOut.write(buffer);
//Override above test if available returns 1
if (stmIn.available() == 1){
bKeepStreaming = true;
}
}//end else some bytes returned.
}//end while
}
/**
* Checks passed-in file name against list of extensions not to zip. Returns
* true if no matches, false if a match to file extension is found.
*/
public static boolean canZip(String fileName){
boolean bCanZip = true;
return bCanZip;
}
public static void main(String[] args){
try {
File flSource = new File(args[0]);
File flTarget = new File(args[1]);
System.out.println("Unzipping file");
unZipZipFileToLocation(flSource, flTarget);
System.out.println("Done");
}
catch (Exception ex){
ex.printStackTrace();
}
}
public static void unZipZipFileToLocation(File zipFile, File targetDir)
throws IOException{
if (! targetDir.isDirectory()){
throw new Exception("Target is not a directory.");
}
FileInputStream flInStr = new FileInputStream(zipFile);
try{
ZipInputStream zis = new ZipInputStream(flInStr);
try{
ZipEntry entry = null;
while((entry = zis.getNextEntry()) != null){
String name = entry.getName();
File newFile = new File(targetDir, name);
if (entry.isDirectory() && ! newFile.exists() ){
newFile.mkdirs();
}
else if (! entry.isDirectory() ){
if (newFile.exists()){
newFile.delete();
}
File parentDir = newFile.getParentFile();
if (! parentDir.exists()){
parentDir.mkdirs();
}
FileOutputStream stmOut = new FileOutputStream(newFile);
try{
simpleInputStreamToOutputStream(zis, stmOut);
}
finally{
stmOut.close();
}
}
}//end while.
}
finally{
zis.close();
}
}
finally{
flInStr.close();
}
}
private static void simpleInputStreamToOutputStream(InputStream stmIn, OutputStream stmOut)
throws IOException{
byte[] buffer = null;
int iBufferSize = 4096;
buffer = new byte[iBufferSize];
boolean bKeepStreaming = true;
while (bKeepStreaming){
int iBytes = stmIn.read(buffer);
if (iBytes == -1){
bKeepStreaming = false;
}
else{
stmOut.write(buffer, 0, iBytes);
}//end else some bytes returned.
}//end while
}
}
Zip up a directory
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* File utilities
*
* @version $Revision: 691982 $
*/
public final class FileUtil {
/**
* Zip up a directory
*
* @param directory
* @param zipName
* @throws IOException
*/
public static void zipDir(String directory, String zipName) throws IOException {
// create a ZipOutputStream to zip the data to
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipName));
String path = "";
zipDir(directory, zos, path);
// close the stream
zos.close();
}
/**
* Zip up a directory path
* @param directory
* @param zos
* @param path
* @throws IOException
*/
public static void zipDir(String directory, ZipOutputStream zos, String path) throws IOException {
File zipDir = new File(directory);
// get a listing of the directory content
String[] dirList = zipDir.list();
byte[] readBuffer = new byte[2156];
int bytesIn = 0;
// loop through dirList, and zip the files
for (int i = 0; i < dirList.length; i++) {
File f = new File(zipDir, dirList[i]);
if (f.isDirectory()) {
String filePath = f.getPath();
zipDir(filePath, zos, path + f.getName() + "/");
continue;
}
FileInputStream fis = new FileInputStream(f);
try {
ZipEntry anEntry = new ZipEntry(path + f.getName());
zos.putNextEntry(anEntry);
bytesIn = fis.read(readBuffer);
while (bytesIn != -1) {
zos.write(readBuffer, 0, bytesIn);
bytesIn = fis.read(readBuffer);
}
} finally {
fis.close();
}
}
}
}