gpt4 book ai didi

java - 如何在 java 中读取/写入异或 txt 文件 UTF8?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:55:01 25 4
gpt4 key购买 nike

到目前为止我做了什么:

我读取了一个带有文本的文件 1,用一个 key 对字节进行异或运算,然后将其写回另一个文件 2。我的问题:我从 file1 读取了例如 'H',字节值为 72;

72 异或 -32 = -88现在我将 -88 写入 file2。当我读取 file2 时,我应该得到 -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;
}

}

最佳答案

您不是按字节读取文件 - 您是按字符读取文件。加密数据不是有效的 UTF-8 编码文本,因此您不应尝试这样阅读它。

同样,您不应该编写任意字节数组,就好像它们是 UTF-8 编码的文本一样。

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

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

关于java - 如何在 java 中读取/写入异或 txt 文件 UTF8?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35311481/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com