我有一個名爲「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