Skip to content

Commit fa044df

Browse files
authored
Merge pull request #6497 from ASJordi/main
#41 - Java
2 parents 570bf62 + 922546b commit fa044df

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import java.io.*;
2+
import java.util.zip.ZipEntry;
3+
import java.util.zip.ZipOutputStream;
4+
5+
public class Main {
6+
7+
public static void main(String[] args) throws IOException {
8+
var res = compressFile("persons.csv");
9+
System.out.println(res ? "File compressed successfully" : "Failed to compress file");
10+
}
11+
12+
public static boolean compressFile(String sourceFile) {
13+
try (FileOutputStream fos = new FileOutputStream("compressed.zip");
14+
ZipOutputStream zipOut = new ZipOutputStream(fos) ) {
15+
16+
File fileToZip = new File(sourceFile);
17+
18+
try (FileInputStream fis = new FileInputStream(fileToZip)) {
19+
20+
ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
21+
zipOut.putNextEntry(zipEntry);
22+
byte[] bytes = new byte[2048];
23+
int length;
24+
25+
while ((length = fis.read(bytes)) >= 0) {
26+
zipOut.write(bytes, 0, length);
27+
}
28+
29+
}
30+
} catch (Exception e) {
31+
System.out.println(e.getMessage());
32+
return false;
33+
}
34+
35+
return true;
36+
}
37+
38+
}

0 commit comments

Comments
 (0)