Как я могу zip файлы в Java и не включать пути файлов
Например, я хочу заархивировать файл, хранящийся в /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;
}
}
Но когда я извлекаю файл, распакованные файлы имеют полный путь.
Мне не нужен полный путь к каждому файлу в zip. Я хочу только имя файла.
Как я могу это сделать?
Ответы
Ответ 1
Здесь:
// 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"
Ответ 2
Вы находите свои исходные данные, используя относительный путь к файлу, а затем устанавливаете Entry в одно и то же. Вместо этого вы должны повернуть источник в объект File, а затем использовать
putNextEntry (новый ZipEntry (sourceFile.getName()))
который даст вам только конечную часть пути (то есть фактическое имя файла)
Ответ 3
Сделайте как сказал Джейсон, или если вы хотите сохранить свою подпись метода, сделайте это так:
out.putNextEntry(new ZipEntry(new File(filename).getName()));
или, используя FileNameUtils.getName из apache commons/io:
out.putNextEntry(new ZipEntry(FileNameUtils.getName(filename)));
Ответ 4
Вы могли бы уйти с доступом к исходным файлам через новый FileInputStream (новый файл (sourceFilePath, sourceFileName)).
Ответ 5
// easy way of zip a file
import 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();
}
}
Ответ 6
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);
}
Ответ 7
Если вы заархивируете два файла с одинаковым именем, но с разными путями, вы столкнетесь с повторяющимися ошибками ввода файлов.