gpt4 book ai didi

java - 如何从字符串写入二进制文件并将其再次检索到字符串?

转载 作者:行者123 更新时间:2023-12-02 10:43:03 31 4
gpt4 key购买 nike

我有一个字符串,希望将其保存到文件中,并能够再次将其检索到字符串中。

我的代码有问题,因为假设我必须编写一些不可读的二进制文件,但是当我打开文件时,我可以读取以下内容:

原始字符串:

[{"name":"asdasd","etName":"111","members":[]}]

在二进制文件中存储字符串:

[ { " n a m e " : " a s d a s d " , " e t N a m e " : " 1 1 1 " , " m e m b e r s " : [ ] } ]

我发现两个问题:

  1. 不以二进制形式存储!我能读懂。它应该是一个困惑的二进制文本,无法读取,但我可以读取它。
  2. 当我检索它时,它的检索方式是字符之间有奇怪的空格。所以它不起作用。

这是我存储字符串的代码:

public static void storeStringInBinary(String string, String path) {
DataOutputStream os = null;
try {
os = new DataOutputStream(new FileOutputStream(path));
os.writeChars(string);
os.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

这是我将其从二进制读取到字符串的代码:

public static String retrieveStringFromBinary(String file) {
String string = null;
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader (file));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
while((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
return stringBuilder.toString();
} catch (Exception e){
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return string;
}

最佳答案

首先,文本文件和二进制文件之间没有真正的区别。文本文件只是一个内容落在与字符对应的字节值范围内的文件。

如果您想加密文件内容,使其无法仅通过 catcat 文件读取,那么您需要选择适当的加密方法。

其次,在 Java 中混合读取器/写入器和流从来都不是一个好主意,选择一种样式并坚持下去。

将字符串保存到文件的函数的问题在于您正在使用 writeChars() 方法,该方法在文档中执行以下操作:

Writes a char to the underlying output stream as a 2-byte value, high byte first. If no exception is thrown, the counter written is incremented by 2.

由于您的字符串由单字节字符组成,这会导致字符串填充空字节,读回时这些字节将转换为空格。如果您将其更改为 writeBytes() 那么你应该得到没有额外空字节的输出。

空字节也会停止您的读取函数的工作,因为由于文件中的前导 0x00,readLine() 函数将在第一次调用时返回 null

关于java - 如何从字符串写入二进制文件并将其再次检索到字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52793969/

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