Project

General

Profile

Statistics
| Revision:

root / FileManager.java @ 1

History | View | Annotate | Download (5.04 KB)

1
import java.io.*;
2
import java.nio.file.*;
3
import java.security.*;
4
import java.nio.charset.*;
5

    
6
public class FileManager {
7

    
8
    public static int chunkSize = 64000;
9

    
10
    // Save byte array chunk to path
11
    public static void saveChunk(byte[] bytes, String path, int chunkN) throws FileNotFoundException, IOException {
12

    
13
        String fileName = path + Integer.toString(chunkN);
14

    
15
        try (FileOutputStream stream = new FileOutputStream(fileName)) {
16
            stream.write(bytes);
17
        }
18

    
19
    }
20

    
21
    // Hash a string with SHA256
22
    public static String hash(String input) {
23

    
24
        try {
25

    
26
            byte[] bytes = digestHashing(input);
27
            return bytesToHex(bytes);
28

    
29
        } catch (Exception e) {
30

    
31
            e.printStackTrace();
32

    
33
        }
34

    
35
        return null;
36

    
37
    }
38

    
39
    // Use MessageDigest to hash in bytes
40
    private static byte[] digestHashing(String input) throws NoSuchAlgorithmException {
41

    
42
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
43
        return digest.digest(input.getBytes(StandardCharsets.UTF_8));
44

    
45
    }
46

    
47
    // Use bytes from MessageDigest to a String
48
    private static String bytesToHex(byte[] hash) {
49

    
50
        StringBuffer hexString = new StringBuffer();
51

    
52
        for (int i = 0; i < hash.length; i++) {
53

    
54
            String hex = Integer.toHexString(0xff & hash[i]);
55

    
56
            if (hex.length() == 1)
57
                hexString.append('0');
58

    
59
            hexString.append(hex);
60

    
61
        }
62

    
63
        return hexString.toString();
64

    
65
    }
66

    
67
    // Delete directory and files
68
    public static void deleteDir(File file) {
69
        File[] contents = file.listFiles();
70
        if (contents != null) {
71
            for (File f : contents) {
72
                if (!Files.isSymbolicLink(f.toPath())) {
73
                    deleteDir(f);
74
                }
75
            }
76
        }
77
        file.delete();
78
    }
79

    
80
    // Create metafile(TODO add more useful arguments)
81
    // Used to reconstruct the file name when Restoring
82
    public static void metaFile(String path, String fileId) throws IOException {
83

    
84
        // Extract file name
85
        int index = path.lastIndexOf("\\");
86
        String fileName = path.substring(index + 1);
87

    
88
        // Create actual file
89
        File file = new File(fileName + ".meta");
90
        if (file.createNewFile()) {
91
            // TODO File created
92
        } else {
93
            // TODO File already exists
94
        }
95

    
96
        // Write data to file
97
        FileWriter writer = new FileWriter(file);
98
        writer.write("Id:" + fileId);
99
        writer.close();
100

    
101
    }
102

    
103
    // Read all bytes of file(generic use)
104
    public static byte[] readFile(String path) {
105

    
106
        Path filePath = Paths.get(path);
107

    
108
        byte[] bytes = null;
109

    
110
        try {
111
            bytes = Files.readAllBytes(filePath);
112
        } catch (Exception e) {
113
            e.printStackTrace();
114
        }
115

    
116
        return bytes;
117
    }
118

    
119
    // Split file in chunks
120
    public static byte[][] split(byte[] fileBytes) {
121

    
122
        // Number of chunks needed is always integer division plus 1 which may be
123
        // partially used or empty
124
        int nChunks = 1 + fileBytes.length / chunkSize;
125

    
126
        // Total bytes
127
        int bytes = fileBytes.length;
128
        int rBytes = 0;
129

    
130
        // Chunks seperated
131
        byte[][] chunks = new byte[nChunks][];
132
        for (int i = 0; i < nChunks; i++) {
133

    
134
            // Calculate proper size
135
            int sizeToCopy = chunkSize;
136
            if (bytes < sizeToCopy)
137
                sizeToCopy = bytes;
138

    
139
            // Chunk with proper size
140
            chunks[i] = new byte[sizeToCopy];
141

    
142
            // Copy to chunk
143
            System.arraycopy(fileBytes, rBytes, chunks[i], 0, sizeToCopy);
144

    
145
            // Remove form total bytes
146
            bytes -= sizeToCopy;
147
            rBytes += sizeToCopy;
148

    
149
        }
150
        return chunks;
151
    }
152

    
153
    // Merge chunks into single byte array
154
    public static byte[] merge(byte[][] chunks) throws IOException {
155

    
156
        // Total bytes
157
        int tBytes = 0;
158
        for (int i = 0; i < chunks.length; i++) {
159
            tBytes += chunks[i].length;
160
        }
161

    
162
        byte[] mergedFile = new byte[tBytes];
163

    
164
        // Written bytes count
165
        int nBytes = 0;
166

    
167
        // Write bytes
168
        for (int i = 0; i < chunks.length; i++) {
169
            System.arraycopy(chunks[i], 0, mergedFile, nBytes, chunks[i].length);
170
            nBytes += chunks[i].length;
171
        }
172

    
173
        return mergedFile;
174
    }
175

    
176
    // Test main for split and merge file
177
    public static void main(String[] args) {
178

    
179
        String fileName = args[0];
180
        Path filePath = Paths.get(fileName);
181
        byte[] fileBytes = null;
182

    
183
        try {
184
            fileBytes = Files.readAllBytes(filePath);
185
        } catch (Exception e) {
186
            e.printStackTrace();
187
        }
188

    
189
        byte[][] chunks = split(fileBytes);
190

    
191
        try {
192
            fileBytes = merge(chunks);
193
        } catch (Exception e) {
194
            e.printStackTrace();
195
        }
196

    
197
    }
198

    
199
}