Reputation: 219
I have a project called "MyApp". MyApp will use a java library I am creating called "MyLibrary". I am writing a function in "MyLibrary" to unzip a zip file in "MyApp"(or whatever app is using "MyLibrary") "resources" dir.
Reading https://community.oracle.com/blogs/kohsuke/2007/04/25/how-convert-javaneturl-javaiofile I cannot create a File via a path because it is not a "physical file". I was using zip4j, but its constructor takes a File or String rather than an InputStream. So I cannot do this:
ZipFile zipfile = new
ZipFile("src/main/resources/compressed.zip");
downloadedZipfile.extractAll("src/main/resources");
java.io.File javadoc and http://www.mkyong.com/java/how-to-convert-inputstream-to-file-in-java/ indicate there isn't a way to convert an InputStream to a File.
Is there another way to access the zip file in the project that is using my library? Thank you in advance.
UPDATE: The zipIn lacks entries, so the while loop won't extract the file out.
InputStream in = getInputStream("", JSON_FILENAME);
ZipInputStream zipIn = new ZipInputStream(in);
ZipEntry entry;
try {
while ((entry = zipIn.getNextEntry()) != null) {
String filepath = entry.getName();
if(!entry.isDirectory()) {
extractFile(zipIn, filepath);
}
else {
File dir = new File(filepath);
dir.mkdir();
}
zipIn.closeEntry();
}
zipIn.close();
} catch (IOException e) {
e.printStackTrace();
}
private void extractFile(ZipInputStream zipIn, String filepath) {
BufferedOutputStream bos = null;
try {
bos = new BufferedOutputStream(new FileOutputStream(filepath));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
byte[] bytesIn = new byte[BUFFER_SIZE];
int read = 0;
try {
while ((read = zipIn.read(bytesIn)) != -1) {
bos.write(bytesIn, 0, read);
}
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Will the file be extracted into the home directory of "MyApp" when using this code that belongs to "MyLibrary"?
Upvotes: 0
Views: 95
Reputation: 32980
If you have a InputStream
to your virtual ZIP file you can use java.util.zip.ZipInputStream
to read the ZIP entries:
InputStream in = ...
ZipInputStream zipIn = new ZipInputStream(in);
ZipEntry entry;
while ((entry = zipIn.getNextEntry()) != null) {
// handle the entry
}
Upvotes: 2