如何在Java中读取/写入UTF8格式的异或文本文件?

3

我目前做的事情:

我读取了一个包含文本的文件1,将字节与密钥进行异或操作,并写回到另一个文件2中。 我的问题是:当我从文件1中读取例如“H”时,其字节值为72;

72 XOR -32 = -88 现在我将-88写入文件2。但是当我读取文件2时,应该得到-88作为第一个字节,但我得到的却是-3。

public byte[] readInput(String File) throws IOException {

    Path path = Paths.get(File);
    byte[] data = Files.readAllBytes(path);
    byte[]x=new byte[data.length ];

    FileInputStream fis = new FileInputStream(File);
    InputStreamReader isr = new InputStreamReader(fis);//utf8
    Reader in = new BufferedReader(isr);
    int ch;
    int s = 0;
    while ((ch = in.read()) > -1) {// read till EOF
        x[s] = (byte) (ch);
    }
    in.close();

    return x;


}




public void writeOutput(byte encrypted [],String file) {
    try {

        FileOutputStream fos = new FileOutputStream(file);
        Writer out = new OutputStreamWriter(fos,"UTF-8");//utf8

        String s = new String(encrypted, "UTF-8");

        out.write(s);
        out.close();
    }
    catch (IOException e) {
        e.printStackTrace();
    }
}



 public byte[]DNcryption(byte[]key,byte[] mssg){

    if(mssg.length==key.length)
    {
        byte[] encryptedBytes= new byte[key.length];

        for(int i=0;i<key.length;i++)
        {
            encryptedBytes[i]=Byte.valueOf((byte)(mssg[i]^key[i]));//XOR

        }
        return encryptedBytes;
    }
    else
    {
        return null;
    }

}   
2个回答

1

你没有以字节的形式读取文件 - 你是以字符的形式读取的。加密数据不是有效的UTF-8编码文本,因此你不应该尝试将其作为这样的文本读取。

同样,你不应该像写入UTF-8编码文本一样写入任意字节数组。

基本上,你的方法具有接受或返回任意二进制数据的签名 - 根本不要使用WriterReader。直接将数据写入流中即可。(而且不要忽略异常,如果你未能写入重要数据,你真的想继续吗?)

我实际上会完全删除你的readInputwriteOutput方法。相反,使用Files.readAllBytesFiles.write


1
非常感谢您,先生! - Khan

0
writeOutput方法中,您将encrypted字节数组转换为UTF-8字符串,这会更改您稍后写入文件的实际字节。尝试使用以下代码片段查看当您尝试将带有负值的字节数组转换为UTF-8字符串时会发生什么:

final String s = new String(new byte[]{-1}, "UTF-8");
System.out.println(Arrays.toString(s.getBytes("UTF-8")));

它将打印类似于[-17,-65,-67]的内容。尝试使用OutputStream将字节写入文件。

new FileOutputStream(file).write(encrypted);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接