I need to get text hash (sha 256), so I need to convert file to its type representation. Is this a fast way to get a byte representation of a file?
public byte[] bEad(String FILENAME) {
RandomAccessFile f=null;
try {
f=new RandomAccessFile(FILENAME, "r");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
byte[] b=new byte[0];
try {
b=new byte[(int) f.length()];
} catch (IOException e) {
e.printStackTrace();
}
try {
f.readFully(b);
f.close();
} catch (IOException e) {
e.printStackTrace();
}
return b;
}
MessageDigest name=MessageDigest.getInstance("SHA-256");
name.update(bEad("D:\crytp.txt"))
1 Answer 1
If have no idea what bEad
means, or why your function is named that way. Also, it should probably be a static
method, since it uses no object state.
By convention, all-caps names, like FILENAME
, should be used only for constants.
Your error handling is bad. Suppose the file does not exist... then what? You'll get a NullPointerException
after printing a stack trace. The correct thing to do is not to catch any of the exceptions. Just declare that the method throws IOException
.
This code could be expressed more succinctly using Files.readAllBytes()
: see this Stack Overflow answer:
byte[] b = Files.readAllBytes(Paths.get(filename));
byte[] hash = MessageDigest.getInstance("SHA-256").digest(b);
Note, however, that that solution, as well as your, scales poorly for large files, since you read the entire file into memory. It would be better to compute the message digest by reading, say, 8192 bytes at a time.
name.update
and instantiating theMessageDigest
? \$\endgroup\$