我的应用程序是一个招标文件系统,其中每个招标编号有一个或多个pdf文件附件。
应用程序是使用struts和mysql在java ee中完成的。
在数据库表中存储用于投标号的每个相关pdf文件的路径。
我想得到所有的pdf文件,并为每个投标号创建一个单独的ZIP文件,以便用户可以下载该zip文件,并有所有相关的文件在一次点击。
我试过谷歌,找到了一个叫ZipOutputStream的东西,但我不明白如何在我的应用程序中使用它。
发布于 2016-05-24 13:01:05
你快到了..。这是一个如何使用ZipOutputStream的小示例。假设您有一个JAVA helper H,它返回包含pdf文件路径(以及相关信息)的数据库记录:
FileOutputStream zipFile = new FileOutputStream(new File("xxx.zip"));
ZipOutputStream output = new ZipOutputStream(zipFile);
for (Record r : h.getPdfRecords()) {
ZipEntry zipEntry = new ZipEntry(r.getPdfName());
output.putNextEntry(zipEntry);
FileInputStream pdfFile = new FileInputStream(new File(r.getPath()));
IOUtils.copy(pdfFile, output); // this method belongs to apache IO Commons lib!
pdfFile.close();
output.closeEntry();
}
output.finish();
output.close();发布于 2016-05-24 13:56:32
签出这段代码,在这里你可以很容易地创建一个zip文件目录:
public class CreateZipFileDirectory {
public static void main(String args[])
{
try
{
String zipFile = "C:/FileIO/zipdemo.zip";
String sourceDirectory = "C:/examples";
//create byte buffer
byte[] buffer = new byte[1024];
FileOutputStream fout = new FileOutputStream(zipFile);
ZipOutputStream zout = new ZipOutputStream(fout);
File dir = new File(sourceDirectory);
if(!dir.isDirectory())
{
System.out.println(sourceDirectory + " is not a directory");
}
else
{
File[] files = dir.listFiles();
for(int i=0; i < files.length ; i++)
{
System.out.println("Adding " + files[i].getName());
FileInputStream fin = new FileInputStream(files[i]);
zout.putNextEntry(new ZipEntry(files[i].getName()));
int length;
while((length = fin.read(buffer)) > 0)
{
zout.write(buffer, 0, length);
}
zout.closeEntry();
fin.close();
}
}
zout.close();
System.out.println("Zip file has been created!");
}
catch(IOException ioe)
{
System.out.println("IOException :" + ioe);
}
}
}https://stackoverflow.com/questions/37404541
复制相似问题