1
|
import java.io.BufferedInputStream;
|
2
|
import java.io.BufferedWriter;
|
3
|
import java.io.File;
|
4
|
import java.io.FileInputStream;
|
5
|
import java.io.FileWriter;
|
6
|
import java.io.IOException;
|
7
|
import java.util.ArrayList;
|
8
|
import java.util.List;
|
9
|
import java.util.NoSuchElementException;
|
10
|
import java.util.zip.ZipException;
|
11
|
import java.util.zip.ZipInputStream;
|
12
|
|
13
|
public class FileWorker {
|
14
|
|
15
|
public static byte[] loadByteArray(File file) throws IOException {
|
16
|
byte buffer[];
|
17
|
|
18
|
/*
|
19
|
* Note.
|
20
|
* For ZIP - the first four bytes should be one of the following combinations:
|
21
|
* 50 4B 03 04
|
22
|
* 50 4B 05 06 (empty archive)
|
23
|
* 50 4B 07 08 (spanned archive)
|
24
|
* Source: https://en.wikipedia.org/wiki/List_of_file_signatures
|
25
|
*/
|
26
|
try {
|
27
|
|
28
|
ZipInputStream zipIS = new ZipInputStream(new FileInputStream(file));
|
29
|
|
30
|
if (zipIS.getNextEntry() == null) {
|
31
|
zipIS.close();
|
32
|
throw new NoSuchElementException();
|
33
|
}
|
34
|
|
35
|
System.out.println("The file is a zip archive...");
|
36
|
List<Byte> _buffer = new ArrayList<Byte>();
|
37
|
while (true) {
|
38
|
int value = zipIS.read();
|
39
|
if (value < 0) {
|
40
|
break;
|
41
|
} else {
|
42
|
_buffer.add((byte) value);
|
43
|
}
|
44
|
}
|
45
|
|
46
|
buffer = new byte[_buffer.size()];
|
47
|
for (int i = 0; i < buffer.length; i++) {
|
48
|
buffer[i] = _buffer.get(i);
|
49
|
}
|
50
|
|
51
|
zipIS.close();
|
52
|
|
53
|
} catch (NoSuchElementException | ZipException e) {
|
54
|
|
55
|
System.out.println("The file is not a zip archive...");
|
56
|
buffer = new byte[(int) file.length()];
|
57
|
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
|
58
|
bis.read(buffer);
|
59
|
bis.close();
|
60
|
|
61
|
}
|
62
|
|
63
|
System.out.println("Bytes from the file were loaded correctly.");
|
64
|
return buffer;
|
65
|
}
|
66
|
|
67
|
public static boolean saveJson(File file, String json) {
|
68
|
boolean retValue = false;
|
69
|
try {
|
70
|
FileWriter fw = new FileWriter(file);
|
71
|
BufferedWriter bw = new BufferedWriter(fw);
|
72
|
bw.write(json);
|
73
|
bw.flush();
|
74
|
bw.close();
|
75
|
retValue = true;
|
76
|
} catch (IOException e) {
|
77
|
e.printStackTrace();
|
78
|
}
|
79
|
return retValue;
|
80
|
}
|
81
|
|
82
|
}
|