如何从非物理文件创建zip文件?
我有一个名为“MyApp”的项目。 MyApp将使用我创建的一个名为“MyLibrary”的Java库。我在“MyLibrary”中编写了一个函数,用于解压缩“MyApp”中的zip文件(或任何应用程序使用“MyLibrary”)“resources”dir。如何从非物理文件创建zip文件?
阅读https://community.oracle.com/blogs/kohsuke/2007/04/25/how-convert-javaneturl-javaiofile我无法通过路径创建文件,因为它不是“物理文件”。我使用zip4j,但它的构造函数使用File或String而不是InputStream。所以,我不能做到这一点:
ZipFile zipfile = new
ZipFile("src/main/resources/compressed.zip");
downloadedZipfile.extractAll("src/main/resources");
java.io.File的javadoc和http://www.mkyong.com/java/how-to-convert-inputstream-to-file-in-java/表示没有办法的InputStream转换成文件。
是否有另一种方式来访问使用我的库的项目中的zip文件?先谢谢你。
UPDATE: zipIn缺少条目,所以while循环不会提取文件。
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();
}
}
会将文件使用此代码属于“在MyLibrary”时,可以提取到“MyApp的”主目录?
如果你有InputStream
到您的虚拟ZIP文件,您可以使用java.util.zip.ZipInputStream
读取ZIP条目:虽然我相当肯定zip4j将支持类似的东西我可以告诉你,truezip确实为确保
InputStream in = ...
ZipInputStream zipIn = new ZipInputStream(in);
ZipEntry entry;
while ((entry = zipIn.getNextEntry()) != null) {
// handle the entry
}
第一行可能使用[Class.getResourceAsStream](https://docs.oracle.com/javase/8/docs/api/java/lang/Class的.html#的getResourceAsStream-java.lang.String-)。例如,'InputStream in = WhateverClassContainsThisCode.class.getResourceAsStream(“/ compressed.zip”);' – VGR
我验证了我的InputStream是正确的,但getNextEntry为null,你能检查上面的代码吗?提取的文件位于何处?谢谢 – Marc
@Marc while循环很好。 (测试:通过使用来自现有压缩文件的'InputStream'运行片段)。否则,通过将其保存到文件并使用ZipFile打开该文件来验证“InputStream” – wero
。 https://truezip.java.net/ – Marged
在您的应用程序的jar文件中访问文件通常由'Class.getResourceAsStream'完成https://docs.oracle.com/javase/7/docs/api/java/lang /Class.html#getResourceAsStream(java.lang.String) – njzk2