02 Kasım
Tek bir dosyayı zipleme
public static void main(String[] args) throws FileNotFoundException, IOException {
// Dosyayı burda belirtiyoruz
String sourceFile = "/home/mintercoder/Desktop/test.txt";
// zip ismini burda belirtiyoruz.
FileOutputStream fos = new FileOutputStream("/home/mintercoder/Desktop/compressed.zip");
ZipOutputStream zipOut = new ZipOutputStream(fos);
File fileToZip = new File(sourceFile);
FileInputStream fis = new FileInputStream(fileToZip);
ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
zipOut.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
zipOut.close();
fis.close();
fos.close();
}
Birden fazla dosyayı zipleme
test.txt
test2.txt
isimli dosyalarımızı compressed.zip isimli dosyaya arşivliyoruz.
```java
public static void main(String[] args) throws FileNotFoundException, IOException {
String sourceFile = "/home/mintercoder/Desktop/test.txt", sourceFile2 = "/home/mintercoder/Desktop/test2.txt";
List<String> fileList = Arrays.asList(sourceFile, sourceFile2);
FileOutputStream fos = new FileOutputStream("/home/kerem/Desktop/compressed.zip");
ZipOutputStream zos = new ZipOutputStream(fos);
for (String fileName : fileList) {
File file = new File(fileName);
FileInputStream fis = new FileInputStream(file);
ZipEntry ze = new ZipEntry(file.getName());
zos.putNextEntry(ze);
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read()) >= 0) {
zos.write(buffer, 0, length);
}
fis.close();
}
zos.close();
fos.close();
}
```
Klasörü zipleme
public static void main(String[] args) throws FileNotFoundException, IOException {
String sourceDirectory = "/home/mintercoder/Desktop/test";
FileOutputStream fos = new FileOutputStream("/home/mintercoder/Desktop/test.zip");
ZipOutputStream zos = new ZipOutputStream(fos);
File fileToZip = new File(sourceDirectory);
zipFile(fileToZip, fileToZip.getName(), zos);
zos.close();
fos.close();
System.out.println("Klasör ziplendi");
}
private static void zipFile(File fileToZip, String fileName, ZipOutputStream zos) throws IOException {
if (fileToZip.isHidden()) {
return;
}
if (fileToZip.isDirectory()) {
if (fileName.endsWith("/")) {
zos.putNextEntry(new ZipEntry(fileName));
zos.closeEntry();
} else {
zos.putNextEntry(new ZipEntry(fileName + "/"));
zos.closeEntry();
}
File[] children = fileToZip.listFiles();
for (File childFile : children) {
zipFile(childFile, fileName + "/" + childFile.getName(), zos);
}
return;
}
FileInputStream fis = new FileInputStream(fileToZip);
ZipEntry ze = new ZipEntry(fileName);
zos.putNextEntry(ze);
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zos.write(bytes, 0, length);
}
fis.close();
}