我有一个场景,我必须将二进制数据转换为 zipfile,我必须在 java 中下载它。
我对如何将二进制文件转换为 zipformate 感到震惊。任何帮助将不胜感激。
我有一个场景,我必须将二进制数据转换为 zipfile,我必须在 java 中下载它。
我对如何将二进制文件转换为 zipformate 感到震惊。任何帮助将不胜感激。
您可以按照下面的示例代码将二进制数据文件转换为 zipfile:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
class ZipTest {
public static void zip(String zipFileName, String inputFile)
throws Exception {
File f = new File(inputFile);
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
zipFileName));
zip(out, f, f.getName());
System.out.println("zip done");
out.close();
}
private static void zip(ZipOutputStream out, File f, String base)
throws Exception {
out.putNextEntry(new ZipEntry(base));
FileInputStream in = new FileInputStream(f);
int b;
while ((b = in.read()) != -1)
out.write(b);
in.close();
}
public static void main(String[] args) {
try {
ZipTest t = new ZipTest();
t.zip("c:\\test.zip", "c:\\1.txt");
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
}
使用此示例将 InputStream 转换为 ZipInputStream:
FileInputStream fin = new FileInputStream(args[i]);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
System.out.println("Unzipping " + ze.getName());
FileOutputStream fout = new FileOutputStream(ze.getName());
for (int c = zin.read(); c != -1; c = zin.read()) {
fout.write(c);
}
zin.closeEntry();
fout.close();
}
zin.close();