2011-05-25 26 views
27

在Scala中是否有一行代碼可以在不使用外部依賴關係的情況下從類路徑中讀取文件,例如公共-io的?如何從無需外部依賴的類路徑中讀取文件?

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

更好地以什麼方式? – Geo 2011-05-25 10:14:18

+2

不依賴於commons-io或者不使用classloader。也許通過支持像Spring類似的語法:「classloader:...」 – mbdev 2011-05-25 10:25:56

回答

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

這不回答「從類路徑讀文件」部分 – mbdev 2011-05-25 09:44:58

+0

@mbdev:更新 – dacwe 2011-05-25 10:12:47

+2

注意,這將使file.xml文件句柄保持打開狀態,即使在字符串已經制作完成。 – pdxleif 2014-04-14 21:31:46

0

Read entire file in Scala? @丹尼爾 - spiewak提出了一個有點不同的做法,我個人比較喜歡比@ dacwe的反應更好。

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

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

然而,我不知道它是否仍然是單線?

4

如果文件位於資源文件夾中(那麼它將位於類路徑的根目錄下),則應該使用類路徑根目錄中的Loader類。

這是代碼行,如果你想獲得的內容(在斯卡拉2.11):

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

在Scala中的其他版本,源類可能是其他類路徑

如果你只是想獲取資源:

val resource = getClass.getClassLoader.getResource("file.xml") 
相關問題