I am using a Java program to generate file hashes. Here is the code:
package main;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import java.nio.file.Files;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class File_Hash_Generator {
final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
public static void main(String args[]) throws IOException {
Scanner inputScanner = new Scanner(System.in);
String[] hashAlgos = { "MD2", "MD5", "SHA-1", "SHA-256", "SHA-384", "SHA-512" };
System.out.print("File Path: ");
String input = inputScanner.next();
input = input.replace("\"", "");
System.out.println();
try {
byte[] fileContents = Files.readAllBytes(new File(input).toPath());
for (String algo : hashAlgos) {
MessageDigest md = MessageDigest.getInstance(algo);
byte[] hash = md.digest(fileContents);
System.out.printf("%s %s%n", algo, bytesToHex(hash));
}
} catch (NoSuchAlgorithmException | IOException e) {
}
}
}
For some reason when I enter in a path where the file or folder has a space, such as:
"C:\Users\User\Downloads\ToBeScanned\DAY N NIGHT.mp3"
The program does not run correctly and instead just terminates without generating any hashes.
EDIT: It was brought up that my question is a duplicate of this question. However, I don't know how this other answer could help me in this instance. If someone could explain to me how to change my code using this separate answer to fix my problem, I'd be grateful.
Any help to fix this is very much appreciated, thanks.