Best way to translate this java code into kotlin

前端 未结 3 568
后悔当初
后悔当初 2021-01-13 15:57
URL url = new URL(urlSpec);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
InputStream in = connection.getInputStream();
int bytesRead = 0;
         


        
3条回答
  •  灰色年华
    2021-01-13 16:49

    You could use something like this

    This operation may be little heavy as a function is created each iteration.

    val url = URL("urlSpec")
    val connection = url.openConnection() as HttpURLConnection
    val `in` = connection.inputStream
    val buffer = ByteArray(1024)
    var bytesRead: Int? = null
    while ({ bytesRead = `in`.read(buffer); bytesRead }() != null) {
            out.write(buffer, 0, bytesRead!!)
    }
    out.close()
    

提交回复
热议问题