Scala String 与 InputStream 互转

陌路散爱 提交于 2020-01-19 20:31:54

1. String 转 InputStream

val is = new ByteArrayInputStream(str.getBytes())

// 转 BufferedInputStream
val bis = new BufferedInputStream(is)

// 打印
Stream.continually(bis.read()).takeWhile(_ != -1).foreach(println(_))

bis.close()
is.close()

 

2. String 转 outoutStream

val is = new ByteArrayInputStream(str.getBytes())
val bis = new BufferedInputStream(is)

// 主要是转outputStream
val bos = new ByteArrayOutputStream()
val buffer = new Array[Byte](4096)
Stream.continually(bis.read(buffer)).takeWhile(_ != -1).foreach(bos.write(buffer, 0, _))

// 转 String 打印
println(bos.toString)

is.close()
bis.close()
bos.close()

 

3. InputStream 转 String

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

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!