Repository navigation
Expand file tree
/
Copy pathSolution.java
More file actions
51 lines (47 loc) · 1.86 KB
/
Copy pathSolution.java
File metadata and controls
51 lines (47 loc) · 1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package com.javarush.task.task31.task3105;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
/*
Добавление файла в архив
*/
public class Solution {
public static void main(String[] args) throws IOException {
String newFileName = Paths.get(args[0]).getFileName().toString();
String newPathInArchive = "new/" + newFileName;
ZipEntry entry;
Map<String, ByteArrayOutputStream> filesInArchive = new HashMap<>();
ZipInputStream zipIn = new ZipInputStream(new FileInputStream(args[1]));
while ((entry = zipIn.getNextEntry()) != null) {
if (entry.getName().endsWith(newFileName)) {
newPathInArchive = entry.getName();
} else {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int length = 0;
byte[] buffer = new byte[1024];
while ((length = zipIn.read(buffer)) != -1) {
baos.write(buffer, 0, length);
}
// baos.write(zipIn.readAllBytes());
filesInArchive.put(entry.getName(), baos);
}
}
zipIn.close();
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(args[1]));
zipOut.putNextEntry(new ZipEntry(newPathInArchive));
Files.copy(Paths.get(args[0]), zipOut);
for (Map.Entry<String, ByteArrayOutputStream> pair : filesInArchive.entrySet()) {
zipOut.putNextEntry(new ZipEntry(pair.getKey()));
pair.getValue().writeTo(zipOut);
}
zipOut.close();
}
}