我有一个名为“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的”主目录?
。 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