您只是不将字节存储为文本。绝不!因为 0x00 可以写为文件中的一个字节,也可以写为字符串,在这种情况下(十六进制)占用了 4 倍的空间。如果您需要这样做,请讨论这个决定会有多糟糕!
如果你能提供一个合理的理由,我会编辑我的答案。
您只会将内容保存为实际文本,如果:
- 它更容易(不是这样)
- 它增加了价值(如果文件大小增加超过 4(空间计数)增加了价值,那么是的)
- 如果用户应该能够编辑文件(那么您将省略“0x”...)
你可以这样写字节:
public static void writeBytes(byte[] in, File file, boolean append) throws IOException {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file, append);
fos.write(in);
} finally {
if (fos != null)
fos.close();
}
}
并像这样阅读:
public static byte[] readBytes(File file) throws IOException {
return readBytes(file, (int) file.length());
}
public static byte[] readBytes(File file, int length) throws IOException {
byte[] content = new byte[length];
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
while (length > 0)
length -= fis.read(content);
} finally {
if (fis != null)
fis.close();
}
return content;
}
因此有:
public static void writeString(String in, File file, String charset, boolean append)
throws IOException {
writeBytes(in.getBytes(charset), file, append);
}
public static String readString(File file, String charset) throws IOException {
return new String(readBytes(file), charset);
}
写入和读取字符串。
请注意,我不使用 try-with-resource 构造,因为 Android 当前的 Java 源代码级别太低了。:(