[英]How to convert scala.io.BufferedSource to java.io.File?
我想在 Scala 項目中使用 Apache POI 庫。
如何將scala.io.BufferedSource
類型轉換為java.io.File
類型?
val file = Source.fromResource("resource.file") // is type scala.io.BufferedSource
// how can I do the conversion here
val workbook = WorkbookFactory.create(file) // requires type java.io.File
這有效,但我想避免指定文件夾路徑,因為文件夾結構是由 sbt 約定處理的:
val file = new File("src/main/resources/resource.file")
val workbook = WorkbookFactory.create(file)
謝謝你的時間🙏
請注意,文件夾結構不是由sbt
處理的。
發生的情況是src/main/resources
的內容src/main/resources
送到 JAR 中,並且可以作為資源在您的類路徑中使用。
如果你按照Source.fromResource
所做的事情做一些事情,你應該能夠得到你需要的東西。
這是供參考的代碼片段:
/** Reads data from a classpath resource, using either a context classloader (default) or a passed one.
*
* @param resource name of the resource to load from the classpath
* @param classLoader classloader to be used, or context classloader if not specified
* @return the buffered source
*/
def fromResource(resource: String, classLoader: ClassLoader = Thread.currentThread().getContextClassLoader())(implicit codec: Codec): BufferedSource =
Option(classLoader.getResourceAsStream(resource)) match {
case Some(in) => fromInputStream(in)
case None => throw new FileNotFoundException(s"resource '$resource' was not found in the classpath from the given classloader.")
}
此代碼可在 GitHub 上找到,這里是最近HEAD
的鏈接: https : //github.com/scala/scala/blob/8a2cf63ee5bad8c8c054f76464de0e10226516a0/src/library/scala/io/Source.scala#L174-L
原則上,您可以使用 Java API 將資源作為流加載,並將其傳遞給WorkbookFactory.create
靜態方法重載,該方法將InputStream
作為某人在評論中提到的輸出。
類似的東西
def maybeResourceAt(path: String): Option[InputStream] =
Option(
Thread.
currentThread().
getContextClassLoader().
getResourceAsStream(path)
)
val input = maybeResourceAt("resource.file").getOrElse(sys.error("oh noes"))
val workbook = WorkbookFactory.create(input)
應該完成工作。
我不確定誰負責關閉InputStream
。 直覺上,我會說create
應該完全使用它,但請仔細檢查庫的文檔以確保。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.