2012-01-14 65 views

Trả lời

17
io.Source.fromFile("file.txt").getLines.size 

Lưu ý rằng getLines trả về một Iterator[String], do đó bạn không thực sự đọc toàn bộ tập tin vào bộ nhớ.

+1

này là hoàn hảo, nhờ !!!! – dave

+2

Tương tự như câu trả lời cho [câu hỏi khác] của bạn (http://stackoverflow.com/q/8865434/115478), điều này cũng làm rò rỉ các bộ mô tả tệp. – leedm777

0
val source = Source.fromFile(new File("file")).getLines 
var n = 1 ; while (source.hasNext) { printf("%d> %s", n, source.next) ; n += 1 } 


val source = Source.fromFile(new File("file")).getLines 
for ((line, n) <- source zipWithIndex) { printf("%d> %s", (n + 1), line) } 
3

cribbing từ another answer I posted:

def lineCount(f: java.io.File): Int = { 
    val src = io.Source.fromFile(f) 
    try { 
    src.getLines.size 
    } finally { 
    src.close() 
    } 
} 

Hoặc, sử dụng scala-arm:

import resource._ 

def firstLine(f: java.io.File): Int = { 
    managed(io.Source.fromFile(f)) acquireAndGet { src => 
    src.getLines.size 
    } 
} 
Các vấn đề liên quan