string 如何从没有外部依赖项的类路径中读取文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6121744/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 01:07:00  来源:igfitidea点击:

How to read a file from classpath without external dependencies?

stringscalaclasspath

提问by mbdev

Is there a one-liner in Scala to read a file from classpath without using external dependencies, e.g. commons-io?

Scala 中是否有一个单行程序可以在不使用外部依赖项(例如 commons-io)的情况下从类路径中读取文件?

IOUtils.toString(getClass.getClassLoader.getResourceAsStream("file.xml"), "UTF-8")

回答by dacwe

val text = io.Source.fromInputStream(getClass.getResourceAsStream("file.xml")).mkString

If you want to ensure that the file is closed:

如果要确保文件已关闭:

val source = io.Source.fromInputStream(getClass.getResourceAsStream("file.xml"))
val text = try source.mkString finally source.close()

回答by fhuertas

If the file is in the resource folder (then it will be in the root of the class path), you should use the Loader class that it is too in the root of the class path.

如果文件位于资源文件夹中(那么它将位于类路径的根目录中),您应该使用 Loader 类,它也位于类路径的根目录中。

This is the code line if you want to get the content (in scala 2.11):

如果您想获取内容,这是代码行(在 Scala 2.11 中):

val content: String  = scala.io.Source.fromInputStream(getClass.getClassLoader.getResourceAsStream("file.xml")).mkString

In other versions of Scala, Source class could be in other classpath

在其他版本的 Scala 中,Source 类可能位于其他类路径中

If you only want to get the Resource:

如果您只想获取资源:

val resource  = getClass.getClassLoader.getResource("file.xml")

回答by Jacek Laskowski

In Read entire file in Scala?@daniel-spiewak proposed a bit different approach which I personally like better than the @dacwe's response.

Scala 中读取整个文件?@daniel-spiewak 提出了一种有点不同的方法,我个人比 @dacwe 的回应更喜欢。

// scala is imported implicitly
import io.Source._

val content = fromInputStream(getClass.getResourceAsStream("file.xml")).mkString

I however wonder whether or not it's still a one-liner?

但是我想知道它是否仍然是单线?