-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathBlob.java
More file actions
68 lines (60 loc) · 2.18 KB
/
Blob.java
File metadata and controls
68 lines (60 loc) · 2.18 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.io.InputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.nio.file.*;
public class Blob {
private static String sha1 = "";
public static String calculateSHA1(String filePath) throws IOException, NoSuchAlgorithmException {
MessageDigest sha1Digest = MessageDigest.getInstance("SHA-1");
try (InputStream fileInputStream = new FileInputStream(filePath)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
sha1Digest.update(buffer, 0, bytesRead);
}
}
byte[] sha1Hash = sha1Digest.digest();
StringBuilder hexString = new StringBuilder();
for (byte hashByte : sha1Hash) {
String hex = Integer.toHexString(0xFF & hashByte);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
sha1 = hexString.toString();
return sha1;
}
public String getSha1 ()
{
return sha1;
}
public static byte[] readFile(String inputFile) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (FileInputStream files = new FileInputStream(inputFile)) {
byte[] br = new byte[1024];
int bytesRead;
while ((bytesRead = files.read(br)) != -1) {
bytes.write(br, 0, bytesRead);
}
}
return bytes.toByteArray();
}
public static String createBlob(String inputFile) throws IOException, NoSuchAlgorithmException {
byte[] data = readFile(inputFile);
String hash = calculateSHA1(new String(data));
File folder = new File("objects");
if (!folder.exists()) {
folder.mkdir();
}
String outputFile = "objects" + File.separator + hash;
Files.write(Paths.get(outputFile), data);
return hash;
}
}