Permalink
Browse files

[JBVFS-155] - A virtual jar file input stream support

  • Loading branch information...
John Bailey
John Bailey committed Apr 5, 2010
1 parent 18044ad commit 3c842cd0597fb1d89e5b1ef0a02416acbbcfd454
@@ -43,6 +43,7 @@
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
+import java.util.jar.JarEntry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
@@ -760,6 +761,42 @@ public static InputStream emptyStream() {
return EMPTY_STREAM;
}
+
+ /**
+ * Get an input stream that will always be consumable as a Zip/Jar file. The input stream will not be an instance
+ * of a JarInputStream, but will stream bytes according to the Zip specification. Using this method, a VFS file
+ * or directory can be written to disk as a normal jar/zip file.
+ *
+ * @param virtualFile The virtual to get a jar file input stream for
+ * @return An input stream returning bytes according to the zip spec
+ * @throws IOException if any problems occur
+ */
+ public static InputStream createJarFileInputStream(final VirtualFile virtualFile) throws IOException {
+ if(virtualFile.isDirectory()) {
+ final VirtualJarInputStream jarInputStream = new VirtualJarInputStream(virtualFile);
+ return new VirtualJarFileInputStream(jarInputStream);
+ }
+ InputStream inputStream = null;
+ try {
+ final byte[] expectedHeader = new byte[4];
+
+ expectedHeader[0] = (byte) (JarEntry.LOCSIG & 0xff);
+ expectedHeader[1] = (byte) ((JarEntry.LOCSIG >>> 8) & 0xff);
+ expectedHeader[2] = (byte) ((JarEntry.LOCSIG >>> 16) & 0xff);
+ expectedHeader[3] = (byte) ((JarEntry.LOCSIG >>> 24) & 0xff);
+
+ inputStream = virtualFile.openStream();
+ final byte[] bytes = new byte[4];
+ final int read = inputStream.read(bytes, 0, 4);
+ if(read < 4 || !Arrays.equals(expectedHeader, bytes)) {
+ throw new IOException("Invalid jar signature " + Arrays.toString(bytes) +" should be " + Arrays.toString(expectedHeader));
+ }
+ } finally {
+ safeClose(inputStream);
+ }
+ return virtualFile.openStream();
+ }
+
/**
* Expand a zip file to a destination directory. The directory must exist. If an error occurs, the destination
* directory may contain a partially-extracted archive, so cleanup is up to the caller.
Oops, something went wrong.

0 comments on commit 3c842cd

Please sign in to comment.