2016-11-15 10 views
1

は、次の点を考慮してくださいため-理解、ガードとRandomAccessFile.readLine

ラインの一定量のテキストファイルは次のように、あります:

あるtest.txt:C B D E F G

H

(各ここで

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 

最初の1行は理解のための割り当てでなければならないため、悲しいことには機能しません。

今や、私の知りたいことは、ある程度の時間までループするか、それともreadLine != nullの条件に基づいて前に停止することが可能なのでしょうか?

構文は壊れていますか?

答えて

2

nullSome(value)Nonevalueに変更されるようにあなたは、OptionrandomAccessFile.readLineをカプセル化することができます。

また、Optionがコレクションとして考えることができるので、あなたがIndexedSeqと理解のために同じでそれを置くことがあります。

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

あなたparse方法に固執する場合は、あなただけgetFilePointerを使用することができますそしてlength

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

関連する問題