如何从Scala中的文件获得第一行 [英] How to get first line from file in Scala

查看:711
本文介绍了如何从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()
  }
}

注意事项:


  1. 该函数返回 Option [String] 而不是 List [String] ,因为它总是返回一个或无。

  2. src 已正确关闭,即使在非常偶然的情况下您可以打开文件,抛出异常

  3. 使用 .find(_ => true)获取 Iterator 不会让我感觉很好,但是没有 nextOption 方法,这比转换为中间列表

  4. IOException 会打开或读取文件。 / li>
  1. The function returns Option[String] instead of List[String], since it always returns one or none. That's more idiomatic Scala.
  2. The src is properly closed, even in the very off chance that you could open the file, but reading throws an exception
  3. Using .find(_ => true) to get the first item of the Iterator doesn't make me feel great, but there's no nextOption method, and this is better than converting to an intermediate List you don't use.
  4. IOExceptions 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆