0
votes

Self explanatory title, what is the int off from the android website, what does it do and why do i need it? I understand first and second argument from bytearrayoutputstream.write but not this one

from the android web: OutputStream Summary

void write(byte[] b, int off, int len)

Writes len bytes from the specified byte array starting at offset off to this output stream.

sample code:

public byte[] getUrlBytes(String urlSpec) throws IOException {
    URL url = new URL(urlSpec);
    HttpURLConnection connection = (HttpURLConnection)url.openConnection();
    try {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        InputStream in = connection.getInputStream();
        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new IOException(connection.getResponseMessage() +
                    ": with " +
                    urlSpec);
        }
        int bytesRead = 0;
        byte[] buffer = new byte[1024];
        while ((bytesRead = in.read(buffer)) > 0) {
            out.write(buffer, 0, bytesRead);
        }
        out.close();
        return out.toByteArray();
    } finally {
        connection.disconnect();
    }
1

1 Answers

1
votes

off is short for "offset", which means the index to start copying from. That, combined with len (or "length"), allows you to copy an arbitrary subsequence instead of the entire source array. For example:

byte[] array = {1,2,3,4};
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(array, 1, 2);    // copy 2 bytes from index 1
System.out.println(Arrays.toString(baos.toByteArray()));
// Output:
// [2, 3]