Ale*_*exx 0 java io groovy zip zipfile
我已尝试过多种方法在Java/Groovy中创建此zip文件.我尝试的前几种方法,来自各种博客/帖子,导致无法打开的损坏的zip文件.所以,我试过这个(下面)看起来相当有前途.sysouts报告传递给FileInputStream的有效文件路径.我不确定是否是传递给ZipOutputStream的FQ路径导致了问题.无论哪种方式,下面是代码,这导致创建小(188kb)zip文件(没有条目).有什么建议?
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
class FileZipper {
public static void makeZip(Set fullyQualifiedFileNames, String zipFileName, String outDir) throws IOException, FileNotFoundException
{
// These are the files to include in the ZIP file
Object[] filenames = fullyQualifiedFileNames.toArray();
String fileSeparator = (String) System.getProperties().get("file.separator");
// Create a buffer for reading the files
byte[] buf = new byte[1024];
// Create the ZIP file
String outFilename = outDir + fileSeparator +zipFileName;
FileOutputStream fos = new FileOutputStream(outFilename);
ZipOutputStream zos = new ZipOutputStream(fos);
System.out.println("Zipping to file " +outFilename);
// Compress the files
for (Object fileName: filenames)
{
System.out.println("Adding file: " + fileName);
FileInputStream fis = new FileInputStream((String)fileName);
// Add ZIP entry to output stream.
String[] nodes = ((String)fileName).split("[/[\\\\]]");
String zipEntry = nodes[nodes.length-1];
System.out.println("Adding Zip Entry: " + zipEntry);
zos.putNextEntry(new ZipEntry((String)fileName));
// Transfer bytes from the file to the ZIP file
int len;
int totalBytes = 0;
while ((len = fis.read(buf)) > 0)
{
totalBytes += len;
zos.write(buf, 0, len);
}
System.out.println("Zipped " +totalBytes +" bytes");
// Complete the entry
zos.closeEntry();
fis.close();
}
// Complete the ZIP file
zos.close();
fos.close();
}
}
Run Code Online (Sandbox Code Playgroud)
小智 8
如果您使用的是Groovy,最简单的方法是使用AntBuilder:
new AntBuilder().zip(
destfile: "myfile.zip",
basedir: "baseDir")
Run Code Online (Sandbox Code Playgroud)
或者从Groovy 1.8开始:
ant.zip(destfile: 'file.zip', basedir: 'src_dir')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2408 次 |
| 最近记录: |