Riccoh
Riccoh

Reputation: 401

ByteString what does the parameters exactly do?

I wanna upload some files which are 30 MB Max to my server with okhttp websocket. The websocket transfer allows String or ByteString only. So I want to convert my file to ByteString and then upload this to my server via websocket(Nodejs).

I use ByteString.of() to convert this byteArray like this.

        val file = "../tmp/file.jpg"

        try {
            val encoded:ByteArray = Files.readAllBytes(Paths.get(file))

            val byteString = ByteString.of(encoded,0,1024)

            ..send data

            Log.d("log1","DATA DONE")
        } catch (e: IOException) {
            Log.d("log1","ERROR:"+e)
        }

But what confuses me is that ByteString function takes 3 parameters.. First: ByteArray Second: Offset Third: Bytecount

My question is what does the last 2 parameters do and the reason behind it? I don't find any clear documentation about this. Just the roadmap that its added.

If you have any links or suggestions please let me know.

Upvotes: 1

Views: 1214

Answers (1)

Sarah Khan
Sarah Khan

Reputation: 866

-Offset is actually where you want to start reading your bytes from. Assume a Text file with the following data

Computer-science World

Quantum Computing

now the offset for the first line is 0 <0,Computer Science World> for the second line the offset will be <23,Quantum Computing>

-ByteCount is the number of bytes you want to count(include)

Let's help you with a piece of simple code

byte[] bytes1 = "Hello, World!".getBytes(Charsets.UTF_8);
ByteString byteString = ByteString.of(bytes1, 2, 9);
// Verify that the bytes were copied out.
Sytem.out.print(byteString.utf8());

Answer is : llo, Worl

So basically, method can be used as a substring. But since you want to send in all the bytes, you can simply use

fun of(vararg data: Byte): ByteString

Upvotes: 2

Related Questions