如何将Scala中的BufferedSource转换为InputStream?

huangapple go评论86阅读模式
英文:

How to covert a BufferedSource in scala to InputStream?

问题

我可以帮你将英文部分翻译成中文:

scala.io.Source.fromResource("keystore.jks")

这行代码是在Scala中从类路径中读取名为 "keystore.jks" 的文件,使用了scala.io.Source.fromResource方法,该方法返回一个BufferedSource对象。你想知道如何将它转换为InputStream,因为某个Java方法需要接受InputStream作为输入。

英文:

I was reading a file from classpath in scala using scala.io.Source using fromResources which provides with a BufferedSource. How can I convert it to an InputStream as a java method invoked expects inputstream.

scala.io.Source.fromResource("keystore.jks")

答案1

得分: 1

你可以将一个BufferedSource转换为byte[],并将其放入ByteArrayInputStream中,类似以下代码可以实现:

import scala.io.Source
import java.io.InputStream

val bufferedSource: Source = Source.fromResource("keystore.jks")
val inputStream: InputStream = new java.io.ByteArrayInputStream(bufferedSource.getLines().mkString("\n").getBytes(java.nio.charset.StandardCharsets.UTF_8))
英文:

You can convert a BufferedSource to byte[] and put it ByteArrayInputStream: something like this will work:

import scala.io.Source
import java.io.InputStream

val bufferedSource: Source = Source.fromResource("keystore.jks")
val inputStream: InputStream = new java.io.ByteArrayInputStream(bufferedSource.getLines().mkString("\n").getBytes(java.nio.charset.StandardCharsets.UTF_8))

huangapple
  • 本文由 发表于 2023年3月4日 04:29:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/75631611.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定