我如何在 Java 中压缩文件而不包含文件路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3018579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can i zip files in Java and not include files paths
提问by Ignacio
For example, I want to zip a file stored in /Users/me/Desktop/image.jpg
例如,我想压缩存储在 /Users/me/Desktop/image.jpg 中的文件
I made this method:
我做了这个方法:
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;
}
}
But when I extract the file, the unzipped files have the full path.
但是当我提取文件时,解压缩的文件具有完整路径。
I don't want the full path of each file in the zip i only want the filename.
我不想要 zip 中每个文件的完整路径,我只想要文件名。
How can I made this?
我怎么能做到这一点?
采纳答案by OscarRyz
Here:
这里:
// Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry(filename));
You're creating the entry for that file using the whole path. If you just use the name ( without the path ) you'll have what you need:
您正在使用整个路径为该文件创建条目。如果您只使用名称(没有路径),您将拥有所需的内容:
// Add ZIP entry to output stream.
File file = new File(filename); //"Users/you/image.jpg"
out.putNextEntry(new ZipEntry(file.getName())); //"image.jpg"
回答by Jason
You're finding your source data using the relative path to the file, then setting the Entry to the same thing. Instead you should turn the source into a File object, and then use
您正在使用文件的相对路径查找源数据,然后将条目设置为相同的内容。相反,您应该将源转换为 File 对象,然后使用
putNextEntry(new ZipEntry(sourceFile.getName()))
putNextEntry(new ZipEntry(sourceFile.getName()))
that'll give you just the final part of the path (ie, the actual file name)
那只会给你路径的最后一部分(即实际的文件名)
回答by Sean Patrick Floyd
Do as Jason said, or if you want to keep your method signature, do it like this:
按照 Jason 说的去做,或者如果你想保留你的方法签名,请这样做:
out.putNextEntry(new ZipEntry(new File(filename).getName()));
or, using FileNameUtils.getNamefrom apache commons/io:
或者,使用来自 apache commons/io 的FileNameUtils.getName:
out.putNextEntry(new ZipEntry(FileNameUtils.getName(filename)));
回答by Tomislav Nakic-Alfirevic
回答by Nishanth Thomas
// easy way of zip a file
import java.io.*;
导入 java.io.*;
import java.util.zip.*;
public class ZipCreateExample{
public static void main(String[] args) throws Exception {
// input file
FileInputStream in = new FileInputStream("F:/ZipCreateExample.txt");;
// out put file
ZipOutputStream out =new ZipOutputStream(new FileOutputStrea("F:/tmp.zip"));
// name of file in zip folder
out.putNextEntry(new ZipEntry("zippedfile.txt"));
byte[] b = new byte[1024];
int count;
// writing files to new zippedtxt file
while ((count = in.read(b)) > 0) {
System.out.println();
out.write(b, 0, count);
}
out.close();
in.close();
}
}
回答by mwendamseke
try {
String zipFile = "/locations/data.zip";
String srcFolder = "/locations";
File folder = new File(srcFolder);
String[] sourceFiles = folder.list();
//create byte buffer
byte[] buffer = new byte[1024];
/*
* To create a zip file, use
*
* ZipOutputStream(OutputStream out) constructor of ZipOutputStream
* class.
*/
//create object of FileOutputStream
FileOutputStream fout = new FileOutputStream(zipFile);
//create object of ZipOutputStream from FileOutputStream
ZipOutputStream zout = new ZipOutputStream(fout);
for (int i = 0; i < sourceFiles.length; i++) {
if (sourceFiles[i].equalsIgnoreCase("file.jpg") || sourceFiles[i].equalsIgnoreCase("file1.jpg")) {
sourceFiles[i] = srcFolder + fs + sourceFiles[i];
System.out.println("Adding " + sourceFiles[i]);
//create object of FileInputStream for source file
FileInputStream fin = new FileInputStream(sourceFiles[i]);
/*
* To begin writing ZipEntry in the zip file, use
*
* void putNextEntry(ZipEntry entry) method of
* ZipOutputStream class.
*
* This method begins writing a new Zip entry to the zip
* file and positions the stream to the start of the entry
* data.
*/
zout.putNextEntry(new ZipEntry(sourceFiles[i].substring(sourceFiles[i].lastIndexOf("/") + 1)));
/*
* After creating entry in the zip file, actually write the
* file.
*/
int length;
while ((length = fin.read(buffer)) > 0) {
zout.write(buffer, 0, length);
}
/*
* After writing the file to ZipOutputStream, use
*
* void closeEntry() method of ZipOutputStream class to
* close the current entry and position the stream to write
* the next entry.
*/
zout.closeEntry();
//close the InputStream
fin.close();
}
}
//close the ZipOutputStream
zout.close();
System.out.println("Zip file has been created!");
} catch (IOException ioe) {
System.out.println("IOException :" + ioe);
}
回答by javanoob
If you zip two files of the same name but with different paths you will run into duplicate file entry errors, though.
但是,如果您压缩两个同名但路径不同的文件,则会遇到重复的文件输入错误。