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) {
    }

}
cezaalp
  • 35
  • 1
  • 6
  • 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). – JB Nizet Oct 28 '17 at 18:48
  • Thank you. OutputStream worked. Why does not Writer work, OutputStream works. Can you explain? – cezaalp Oct 29 '17 at 12:39
  • 1
    I already have. Re-read my comment. – JB Nizet Oct 29 '17 at 12:40

1 Answers1

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.

laune
  • 30,276
  • 3
  • 26
  • 40