Scala String 与 InputStream 互转

﹏ヽ暗。殇╰゛Y 2021-09-23 18:50 571阅读 0赞

1. String 转 InputStream

  1. val is = new ByteArrayInputStream(str.getBytes())
  2. // 转 BufferedInputStream
  3. val bis = new BufferedInputStream(is)
  4. // 打印
  5. Stream.continually(bis.read()).takeWhile(_ != -1).foreach(println(_))
  6. bis.close()
  7. is.close()

#

2. String 转 outoutStream

  1. val is = new ByteArrayInputStream(str.getBytes())
  2. val bis = new BufferedInputStream(is)
  3. // 主要是转outputStream
  4. val bos = new ByteArrayOutputStream()
  5. val buffer = new Array[Byte](4096)
  6. Stream.continually(bis.read(buffer)).takeWhile(_ != -1).foreach(bos.write(buffer, 0, _))
  7. // 转 String 打印
  8. println(bos.toString)
  9. bos.close()
  10. bis.close()
  11. is.close()

3. InputStream 转 String

  1. val br = new BufferedReader(new InputStreamReader(new FileInputStream("strPath")))
  2. var result = new StringBuilder
  3. result += Stream.continually(br.readLine()).takeWhile(_ != null).mkString("\n")
  4. println(result.toString)
  5. bufferedReader.close()

发表评论

表情:
评论列表 (有 0 条评论,571人围观)

还没有评论,来说两句吧...

相关阅读