如何从Scala中的文件获得第一行 [英] How to get first line from file in Scala
本文介绍了如何从Scala中的文件获得第一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在Scala中获取CSV文件中的第一行,我将如何做,而不使用getLine(0)(它已被弃用)?
I'd like to get just the first line from a CSV file in Scala, how would I go about doing that without using getLine(0) (it's deprecated)?
推荐答案
FWIW,这里是我会做的(坚持标准库):
FWIW, here's what I would do (sticking w/ the standard library):
def firstLine(f: java.io.File): Option[String] = {
val src = io.Source.fromFile(f)
try {
src.getLines.find(_ => true)
} finally {
src.close()
}
}
注意事项:
- 该函数返回
Option [String]
而不是List [String]
,因为它总是返回一个或无。 -
src
已正确关闭,即使在非常偶然的情况下您可以打开文件,抛出异常 - 使用
.find(_ => true)
获取Iterator
不会让我感觉很好,但是没有nextOption
方法,这比转换为中间列表
。 -
IOException
会打开或读取文件。 / li>
- The function returns
Option[String]
instead ofList[String]
, since it always returns one or none. That's more idiomatic Scala. - The
src
is properly closed, even in the very off chance that you could open the file, but reading throws an exception - Using
.find(_ => true)
to get the first item of theIterator
doesn't make me feel great, but there's nonextOption
method, and this is better than converting to an intermediateList
you don't use. IOException
s opening or reading the file are passed along.
我也建议您使用 scala-arm 库,为您提供更好的API来管理资源,并在需要时自动关闭文件。
I also recommend using the scala-arm library to give you a better API for managing resources and automagically closing files when you need to.
import resource._
def firstLine(f: java.io.File): Option[String] = {
managed(io.Source.fromFile(f)) acquireAndGet { src =>
src.getLines.find(_ => true)
}
}
这篇关于如何从Scala中的文件获得第一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文