在Kotlin中,可以使用ByteArrayInputStream类将字符串转换为InputStream。下面是一个示例代码: 代码语言:txt 复制 fun stringToInputStream(str: String): InputStream { val bytes = str.toByteArray() return ByteArrayInputStream(bytes) } 在这个示例中,我们首先使用toByteArray()函数将字符串转换为字节数组...
依赖Java版本没有错,但在可能的情况下使用更多的kotlin惯用法
fun readDictionary(file: File): Map<String, *> =file.inputStream().use { TODO("Read a mapping of strings to arbitrary elements.") }//我们已将存有一些 `Int` 的映射保存到该文件val intsFile = File("ints.dictionary")//Warning: Unchecked cast: `Map<String, *>` to `Map<String, Int...
importjava.io.DataOutputStreamimportjava.io.InputStreamimportjava.net.Socketfunmain(){valsocket=Socket("www.example.com",80)valoutputStream=socket.getOutputStream()valinputStream:InputStream=socket.getInputStream()valdataOutputStream=DataOutputStream(outputStream)dataOutputStream.writeBytes("GET / HTTP/...
(): String = withContext(Dispatchers.IO) { val url = URL("https://api.example.com/data") val connection = url.openConnection() val inputStream = connection.getInputStream() val reader = BufferedReader(InputStreamReader(inputStream)) val stringBuilder = StringBuilder() var line: String?
urlConn.getInputStream())); while ((line = buffer.readLine()) != null) { sb.append(line); } } catch (Exception e) { e.printStackTrace(); Log.i("TAG", e.getMessage()); JSONObject obj = new JSONObject(); try { obj.put("success", "false"); ...
def output = p.inputStream.text 1. 2. 在Kotlin 中,目前还没有对 String 类和 Process 扩展这样的函数。其实扩展这样的函数非常简单。我们完全可以自己扩展。 首先,我们来扩展 String 的 execute() 函数。 fun String.execute(): Process { val runtime = Runtime.getRuntime() ...
byteArrayOutputStream.close()returnserStr }/** * 反序列化对象 * @param str * * * @return * * * @throws IOException * * * @throws ClassNotFoundException*/@Suppress("UNCHECKED_CAST") @Throws(IOException::class, ClassNotFoundException::class)privatefun <A>deSerialization(str: String): A ...
首先通过File对象获取InputStream实例,通过inputStream获取bufferedReader,最后通过bufferedReader.use高级函数读取文件内容,并返回String 如果需要逐行读取,则需要以下方式: val inputStream:InputStream=File("kotlin.txt").inputStream() val lineList=mutableListOf() ...
await() } fun download(url: String): String { var urlConn : HttpURLConnection? = null var strBuffer = StringBuffer() var inputStream: InputStream? = null var buffer: BufferedReader? = null var inputReader: InputStreamReader? = null try { urlConn = URL(url).openConnection() as Http...