简体   繁体   中英

Best way to encode

I have an array of bytes that contains negative numbers that I need to write to a file and read back into a byte array.

Imagine that I have 10 byte arrays of length 128, including negative numbers.

What would be the best way to write the ten arrays to the same file, such that I could read the file and create the same ten byte arrays again? I know that there will always be of length 128, so that is not an issue.

I currently tried putting them all into one string, encoding it with base 64, and writing that to file. However, when I read the file and decoded it, it didn't seem to interpret it properly (the first array was in order, the other was not).

Any ideas?

Just write them out directly to an OutputStream - there's no need to encode them:

// Or wherever you get them from
byte[][] arrays = new byte[10][128];
...

for (byte[] array : arrays) {
    outputStream.write(array);
}

Then when reading (with an 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;
}

Note that you can't just issue 10 calls to InputStream.read and assume it will read 128 bytes each time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM