2017-10-28 114 views
2

首先我创建签名(字节[]签名)假。然后我将这个签名写入文件。我从这个文件读取签名并给它另一个变量(byte [] signatureCopy)。但是当我比较这两个变量时,它返回false。我该如何解决它?阵列等于返回相同的字节数组

但是,当我打印屏幕,它的外观一样。

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

代码:

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

功能;

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

} 
+2

请勿使用Writer写入二进制数据。使用OutputStream。新字符串(签名)是一种有损操作,因为字节数组不代表使用默认字符集编码的字符,并且println()会添加EOL字符。 –

+0

谢谢。 OutputStream工作。为什么Writer不工作,OutputStream的作品。你可以解释吗? – cezaalp

+1

我已经拥有。重新阅读我的评论。 –

回答

5

您正在使用println编写,它将向字符串添加CR-LF或LF。

readAllBytes真的会读取所有字节,包括CR-LF或LF。

因此,阵列不同,虽然印刷的字符串看起来是一样的。 (虽然,你应该注意额外的换行符。)

另外:如果你将字节转换为字符串,一些编码生效,这可能会或可能不会产生你想要什么。如果您的签名应该是一个字节数组,请不要将其转换为字符串进行打印,而应以十六进制格式将字节值打印为数字值。

+0

很好地解释。我还想知道为什么它不打印“真实”。 – Razib