我想在 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)
謝謝你的時間??
uj5u.com熱心網友回復:
請注意,檔案夾結構不是由sbt.
發生的情況是, 的內容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-L184
原則上,您可以使用 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應該完全消耗它,但要仔細檢查圖書館的檔案以確保。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/358549.html
標籤:爪哇 斯卡拉 apache-poi
