-1
\$\begingroup\$

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"))
\$\endgroup\$
  • 1
    \$\begingroup\$ Code Review is about improving existing, working code. Code Review is not the site to ask for help in fixing or changing what your code does. Have you tested this code? Does it work for you? It sounds like you are unsure about what your code does. \$\endgroup\$ – Simon Forsberg Sep 25 '17 at 17:06
  • \$\begingroup\$ it's working and run fast, (I share my solution). \$\endgroup\$ – sherif Sep 25 '17 at 17:19
  • \$\begingroup\$ Can you please show your real code, where you are calling the name.update and instantiating the MessageDigest? \$\endgroup\$ – Simon Forsberg Sep 25 '17 at 18:05
  • \$\begingroup\$ Do you want to get feedback on your code, or what exactly is your purpose of posting this here? \$\endgroup\$ – Simon Forsberg Sep 25 '17 at 18:05
  • \$\begingroup\$ I need a feedback \$\endgroup\$ – sherif Sep 25 '17 at 18:31
0
\$\begingroup\$

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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.