-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathblob.java
More file actions
74 lines (67 loc) · 2.26 KB
/
blob.java
File metadata and controls
74 lines (67 loc) · 2.26 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
69
70
71
72
73
74
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
public class Blob {
private String sha;
public Blob(String inputFile) throws IOException {
try {
File file = new File(inputFile);
BufferedReader reader = new BufferedReader(new FileReader(file));
StringBuilder fileInfo = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
line = line.trim();
fileInfo.append(line).append("");
}
reader.close();
String hashed = hashStringToSHA1(fileInfo.toString());
write(hashed, fileInfo);
sha = hashed;
} catch (IOException e) {
e.printStackTrace();
}
}
public static void write(String hashed, StringBuilder inside) {
try {
String newFile = hashed;
File objects = new File("./objects");
objects.mkdirs();
FileWriter write = new FileWriter("./objects/" + newFile);
write.write(inside.toString());
write.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// This is from google, as allowed
public static String hashStringToSHA1(String input) {
try {
MessageDigest sha1Digest = MessageDigest.getInstance("SHA-1");
byte[] inputBytes = input.getBytes();
sha1Digest.update(inputBytes);
byte[] hashBytes = sha1Digest.digest();
StringBuilder hexString = new StringBuilder();
for (byte hashByte : hashBytes) {
String hex = Integer.toHexString(0xFF & hashByte);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
public String getSha() {
return sha;
}
}