2014-12-08 21 views
61

Tôi có một cấu trúc thư mục như dưới đây:Cách đọc tệp từ thư mục tài nguyên trong Scala?

- main 
-- java 
-- resources 
-- scalaresources 
--- commandFiles 

và trong các thư mục mà tôi có tập tin của tôi rằng tôi phải đọc. Đây là mã:

def readData(runtype: String, snmphost: String, comstring: String, specificType: String): Unit = { 
    val realOrInvFile = "/commandFiles/snmpcmds." +runtype.trim // these files are under commandFiles folder, which I have to read. 
    try { 
     if (specificType.equalsIgnoreCase("Cisco")) { 
     val specificDeviceFile: String = "/commandFiles/snmpcmds."+runtype.trim+ ".cisco" 
     val realOrInvCmdsList = scala.io.Source.fromFile(realOrInvFile).getLines().toList.filterNot(line => line.startsWith("#")).map{ 
      //some code 
     } 
     val specificCmdsList = scala.io.Source.fromFile(specificDeviceFile).getLines().toList.filterNot(line => line.startsWith("#")).map{ 
      //some code 
     } 
     } 
    } catch { 
     case e: Exception => e.printStackTrace 
    } 
    } 
} 

Trả lời

115

Tài nguyên trong Scala hoạt động chính xác như trong Java. Cách tốt nhất là thực hiện theo các phương pháp hay nhất về Java và đặt tất cả tài nguyên vào src/main/resourcessrc/test/resources.

Ví dụ cấu trúc thư mục:

testing_styles/ 
├── build.sbt 
├── src 
│   └── main 
│    ├── resources 
│    │   └── readme.txt 

Scala 2.12.x

Để đọc các nguồn lực vật Nguồn cung cấp các phương pháp fromResource.

import scala.io.Source 
val readmeText : Iterator[String] = Source.fromResource("readme.txt").getLines 

phiên bản trước

Để đọc tài nguyên mà bạn có thể sử dụng getClass.getResourcegetClass.getResourceAsStream.

val stream : InputStream = getClass.getResourceAsStream("/readme.txt") 
val lines = scala.io.Source.fromInputStream(stream).getLines 

Hãy ghi nhớ rằng getResourceAsStream cũng hoạt động tốt khi các nguồn lực là một phần của một jar, getResource, mà trả về một URL mà thường được sử dụng để tạo ra một tập tin có thể dẫn đến những vấn đề đó.

phản hồi lỗi đẹp hơn (2.12.x)

Để tránh undebuggable Java NPEs (Java là khủng khiếp như vậy), hãy xem xét:

import scala.io.Source 
import scala.util.Try 

def niceFeedbackReadResource(resource: String): List[String] = 
    Try(Source.fromResource(resource).getLines.toList) 
    .recover(throw new FileNotFoundException(resource)) 

Để có được FNFEs có ý nghĩa để thay thế.

Đối với mã sản xuất, tôi cũng khuyên bạn nên đảm bảo rằng nguồn được đóng lại.

+0

Những loại vấn đề có thể xảy ra nếu sử dụng getResource và biến nó thành một tập tin? bạn có thể cung cấp một liên kết? – akauppi

+2

Trong một số trường hợp, một Con trỏ rỗng: http://stackoverflow.com/questions/941754/how-to-get-a-path-to-a-resource-in-a-java-jar-file –

+0

Mã này có thể là để mở trình xử lý mở cho getResourceAsStream. – Sisso

13

Đối Scala> = 2.12, sử dụng Source.fromResource:

scala.io.Source.fromResource("located_in_resouces.any") 
+7

Quan trọng: với' Source.fromResource' bạn không đặt dấu gạch chéo chuyển tiếp ban đầu mà bạn có với 'getResourceAsStream'. – vossad01

+5

Và lưu ý rằng đây là 2,12+ – rbellamy

Các vấn đề liên quan