1

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
0

2 Answers 2

2

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();
Sign up to request clarification or add additional context in comments.

2 Comments

Reading the whole file by one byte after another is really bad and very slow practice.
This doesn't work. My buffer will contain the correct values [-119, 45, 67, ...] when shown as a string, but after toByteArray(), result contains [91, 45, 49, ...]. In debug, the string representation of buffer is correct, but the actual values are wrong.
1

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.