2016-11-15 40 views
1

考慮以下幾點:換理解,防護件和RandomAccessFile.readLine

有與一定量的線的文本文件,如:

的test.txt: 一個 b Ç d Ë ˚F 克 ħ

(各在有自己的行)

再有就是用於解析以下類:

class MyAwesomeParser 
{ 
    def parse(fileName: String, readLines: Int): IndexedSeq[String] = 
    { 
     val randomAccessFile = new RandomAccessFile(fileName, "r") 

     val x: IndexedSeq[String] = for 
     { 
      x <- 0 until readLines 
      r = randomAccessFile.readLine() 
     } yield r 

     x 
    } 
} 

來這裏測試:

class MyAwesomeParserTest extends WordSpec 
{ 
    "MyAwesomeParser" when { 
    "read" should { 
     "parse only specified number of lines" in { 
     val parser = new EdgeParser("") 
     val x = parser.parse("test.txt", 5) 

     assert(x.size == 5) 
     } 
    } 

    "MyAwesomeParser" when { 
    "read" should { 
     "parse only until end of file" in { 
     val parser = new EdgeParser("") 
     val x = parser.parse("test.txt", 10) 

     assert(x.size == 8) 
     } 
    } 
    } 
} 

第二個測試是有問題的。現在當然你說,你錯過了一個後衛在這裏......好吧,好吧,如果我添加

x <- 0 until readLines if randomAccessFile.readLine != null 

的實現,那麼它會跳過幾行,因爲已經的readLine消耗行。

r = randomAccessFile.readLine 
    x <- 0 until readLines if r != null 

不會悲傷地工作,因爲第一行必須是理解的任務。

現在我想知道,是否甚至有可能用於理解循環,直到基於那個readLine != null條件循環直到給定的次數或停止爲止?

我的語法剛剛壞了嗎?

回答

2

您可以在Option封裝randomAccessFile.readLine,使null將變更爲NonevalueSome(value)

此外,Option可以看作是一個集合,所以你可以把它放在同爲理解爲IndexedSeq

for { 
    x <- 0 until readLines 
    r <- Option(randomAccessFile.readLine()) 
} yield r 
3

如果你要堅持你parse方法,你可以只使用getFilePointerlength

def parse(fileName: String, readLines: Int): IndexedSeq[String] = 
{ 
    val randomAccessFile = new RandomAccessFile(fileName, "r") 

    val x: IndexedSeq[String] = for 
    { 
     x <- 0 until readLines if randomAccessFile.getFilePointer < randomAccessFile.length 
     r = randomAccessFile.readLine() 
    } yield r 

    x 
} 

然而,而不是重新發明輪子,我建議你只使用scala.io.Source

def parse(fileName: String, readLines: Int): Iterator[String] = 
    Source.fromFile(fileName).getLines.take(readLines) 
+0

啊,廢話..我試圖提供一個小例子,但我不想爲我的具體問題工作,而是一個通用的解決方案 – Sorona