Adam Johns
Adam Johns

Reputation: 36353

Read byte values contained in file into byte array

If I have a file that contains the exact byte[] data that I want:

[-119, 45, 67, ...]

How can I read those values into a byte array? Do I have to read them as a String, and then convert those String values to byte values?

This is what I'm currently doing, and it works, but slowly:

BufferedReader reader = null;
    String mLine = null;
    AssetManager assetManager = CustomApplication.getCustomAppContext().getAssets();

    try {
        reader = new BufferedReader(new InputStreamReader(assetManager.open(fileName)));
        mLine = reader.readLine();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    String[] byteValues = mLine.substring(1, mLine.length() - 1).split(",");
    byte[] imageBytes = new byte[byteValues.length];

    for (int i = 0; i < imageBytes.length; i++) {
        imageBytes[i] = Byte.valueOf(byteValues[i].trim());
    }

    return imageBytes;

UPDATE: There seems to be a misunderstanding of what I want to accomplish. My file contains the EXACT byte data I want in my final byte array. For example, I want to convert a file with exactly

[-119, 45, 67, ...]

into a byte[] called result with

result[0] = -119
result[1] = 45
result[2] = 67

Upvotes: 1

Views: 1193

Answers (2)

V&#225;clav Hodek
V&#225;clav Hodek

Reputation: 668

Much faster version of Eng.Fouad code:

BufferedInputStream bis = new BufferedInputStream(assetManager.open(fileName));
ByteArrayOutputStream buffer = new ByteArrayOutputStream();

int size;
byte[] buffer = new byte[4096];

while((size = bis.read(buffer)) != -1) {
    buffer.write(buffer, 0, size);
}

bis.close();
buffer.close();

byte[] result = buffer.toByteArray();

Upvotes: 1

Eng.Fouad
Eng.Fouad

Reputation: 117597

BufferedReader is used to read char units. Use BufferedInputStream which reads byte units and use ByteArrayOutputStream to help you filling the byte array:

BufferedInputStream bis = new BufferedInputStream(assetManager.open(fileName));
ByteArrayOutputStream buffer = new ByteArrayOutputStream();

int theByte;

while((theByte = bis.read()) != -1)
{
    buffer.write(theByte);
}

bis.close();
buffer.close();

byte[] result = buffer.toByteArray();

Upvotes: 2

Related Questions