我有一个包含负数的字节数组,我需要将其写入文件并读回字节数组。
想象一下,我有 10 个长度为 128 的字节数组,包括负数。
将十个数组写入同一个文件的最佳方法是什么,以便我可以读取文件并再次创建相同的十字节数组?我知道总会有 128 的长度,所以这不是问题。
我目前尝试将它们全部放入一个字符串中,使用 base 64 对其进行编码,然后将其写入文件。但是,当我读取文件并对其进行解码时,它似乎没有正确解释它(第一个数组是有序的,另一个不是)。
有任何想法吗?
只需将它们直接写出OutputStream
- 无需对它们进行编码:
// Or wherever you get them from
byte[][] arrays = new byte[10][128];
...
for (byte[] array : arrays) {
outputStream.write(array);
}
然后在阅读时(带有InputStream
):
byte[][] arrays = new byte[10][];
for (int i = 0; i < arrays.length; i++) {
arrays[i] = readExactly(inputStream, 128);
}
...
private static byte[] readExactly(InputStream input, int size) throws IOException {
byte[] ret = new byte[size];
int bytesRemaining = size;
while (bytesRemaining > 0) {
int bytesRead = input.read(ret, size - bytesRemaining, bytesRemaining);
if (bytesRead == -1) {
throw new IOException("Ran out of data");
}
}
return ret;
}
请注意,您不能只发出 10 次调用InputStream.read
并假设它每次都会读取 128 个字节。