将二进制值转换为可下载的 zip 文件
Converting binary value to downloadable zipfile
我有一个场景,我必须将二进制数据转换为 zip 文件,我必须在 java 中下载它。
我对如何将二进制文件转换为 zipformate 的部分感到震惊。任何帮助将不胜感激。
您可以按照下面的示例代码将您的二进制数据文件转换为 zip 文件:
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();
我有一个场景,我必须将二进制数据转换为 zip 文件,我必须在 java 中下载它。
我对如何将二进制文件转换为 zipformate 的部分感到震惊。任何帮助将不胜感激。
您可以按照下面的示例代码将您的二进制数据文件转换为 zip 文件:
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();