2

First I create a signature (byte[] signature). Then I write this signature to the file. I read the signature from this file and give it another variable (byte [] signatureCopy). But when I compare these two variables, it returns false. How can I resolve it?

But when I print the screen, it looks the same.

System.out.println (new String (signature));
System.out.println (new String (signatureCopy));

Code:

    byte[] signature = this.signature(data);        
    FileUtil.writeRegistryFileSigned(path, signature);
    byte[] signatureCopy = FileUtil.readSignatureInRegistryFile(path);
    System.out.println(Arrays.equals(signature, signatureCopy)); //FALSE

Functions;

public static byte[] readSignatureInRegistryFile(String filePath){
    byte[] data = null;
    try {
        data = Files.readAllBytes(Paths.get(filePath));
    } catch (IOException e) {
        e.printStackTrace();
    }
    return data;        
}


public static void writeRegistryFileSigned(String filePath, byte[] signature) {
    File fileRegistry = new File(filePath);
    try {
        fileRegistry.createNewFile();
    } catch (IOException e1) {

    }
    try (FileWriter fw = new FileWriter(fileRegistry, true);
            BufferedWriter bw = new BufferedWriter(fw);
            PrintWriter out = new PrintWriter(bw)) {            
        out.println(new String(signature));

    } catch (IOException e) {
    }

}
3
  • 2
    Don't use a Writer to write binary data. use an OutputStream. new String(signature) is a lossy operation that doesn't make sense (since the byte array does NOT represent characters encoded using your default charset), and println() adds EOL character(s). Commented Oct 28, 2017 at 18:48
  • Thank you. OutputStream worked. Why does not Writer work, OutputStream works. Can you explain? Commented Oct 29, 2017 at 12:39
  • 1
    I already have. Re-read my comment. Commented Oct 29, 2017 at 12:40

1 Answer 1

5

You are writing using println which will add a CR-LF or LF to the String.

readAllBytes will really read all bytes, including the CR-LF or LF.

Therefore, the arrays differ, although the printed strings look the same. (Although, you should notice the extra line feed.)

Moreover: If you convert bytes to a String, some encoding is in effect and this may or may not produce what you want. If your signature is supposed to be a byte array, don't convert it to String for printing, rather print the byte values as numeric values, in hexadecimal.

Sign up to request clarification or add additional context in comments.

1 Comment

nicely explained. I was also wondering why its not printing 'true'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.