例如,我想压缩存储在/Users/me/Desktop/image.jpg中的文件
我做了这个方法:
public static Boolean generateZipFile(ArrayList<String> sourcesFilenames, String destinationDir, String zipFilename){
// Create a buffer for reading the files
byte[] buf = new byte[1024];
try {
// VER SI HAY QUE CREAR EL ROOT PATH
boolean result = (new File(destinationDir)).mkdirs();
String zipFullFilename = destinationDir + "/" + zipFilename ;
System.out.println(result);
// Create the ZIP file
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFullFilename));
// Compress the files
for (String filename: sourcesFilenames) {
FileInputStream in = new FileInputStream(filename);
// Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry(filename));
// Transfer bytes from the file to the ZIP file
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
// Complete the entry
out.closeEntry();
in.close();
} // Complete the ZIP file
out.close();
return true;
} catch (IOException e) {
return false;
}
}
但是当我解压缩文件时,解压缩后的文件具有完整的路径。
我不想要压缩包中每个文件的完整路径,我只需要文件名。
我该怎么做呢?
发布于 2010-06-11 06:40:04
这里:
// Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry(filename));
您将使用整个路径为该文件创建条目。如果您只使用名称(不包括路径),您将获得所需的内容:
// Add ZIP entry to output stream.
File file = new File(filename); //"Users/you/image.jpg"
out.putNextEntry(new ZipEntry(file.getName())); //"image.jpg"
发布于 2010-06-11 05:26:33
您将使用文件的相对路径查找源数据,然后将条目设置为相同的内容。相反,您应该将源文件转换为File对象,然后使用
新建(putNextEntry ZipEntry(sourceFile.getName()
这将只给你路径的最后一部分(即实际的文件名)
发布于 2010-06-11 05:39:59
做as Jason said,或者如果你想保留你的方法签名,像这样做:
out.putNextEntry(new ZipEntry(new File(filename).getName()));
或者,使用apache commons/io中的FileNameUtils.getName:
out.putNextEntry(new ZipEntry(FileNameUtils.getName(filename)));
https://stackoverflow.com/questions/3018579
复制相似问题