当前位置: 代码迷 >> 综合 >> Scala String 与 InputStream
  详细解决方案

Scala String 与 InputStream

热度:89   发布时间:2024-01-26 10:27:14.0

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()

 

  相关解决方案