Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

android - 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.

question from:https://stackoverflow.com/questions/65836002/bytestring-what-does-the-parameters-exactly-do

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

-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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...