
how to calculate SHA256 of a file in java

Hello Friend,
Try the following code:
import java.io.*; import java.security.MessageDigest;
public class Compute{ public static void main(String[]args)throws Exception{ int by = 16384; try { RandomAccessFile file = new RandomAccessFile("data.txt", "r"); MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] buffer = new byte[by];
byte[] bytes = null;
long read = 0;
long offset = file.length();
int size;
while (read < offset) {
size = (int) (((offset - read) >= by) ? by : (offset - read));
file.read(buffer, 0, size);
md.update(buffer, 0, size);
read += size;
}
file.close();
bytes = new byte[md.getDigestLength()];
bytes = md.digest();
System.out.println(read);
}
catch (Exception e) {
System.out.println(e);
} } }
Hope that it will be helpful for you.
Thanks

Hello Friend,
import java.io.*;
import java.security.MessageDigest;
public class Compute{
public static void main(String[]args)throws Exception{
int by = 16384;
try {
RandomAccessFile file = new RandomAccessFile("data.txt", "r");
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] buffer = new byte[by];
byte[] bytes = null;
long read = 0;
long offset = file.length();
int size;
while (read < offset) {
size = (int) (((offset - read) >= by) ? by : (offset - read));
file.read(buffer, 0, size);
md.update(buffer, 0, size);
read += size;
}
file.close();
bytes = new byte[md.getDigestLength()];
bytes = md.digest();
System.out.println(read);
}
catch (Exception e) {
System.out.println(e);
}
}
}
Thanks
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.