English 中文(简体)
如何从Schala的档案中进入第一线
原标题:How to get first line from file in Scala

我只想从科萨拉的CSV档案中找到第一线,我如何在没有使用Line(0)的情况下这样做?

最佳回答

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. 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图书馆,在你需要时,向您提供更好的预报,以便管理资源和自动结案档案。

import resource._

def firstLine(f: java.io.File): Option[String] = {
  managed(io.Source.fromFile(f)) acquireAndGet { src =>
    src.getLines.find(_ => true)
  }
}
问题回答

如果你在使用档案后不注意释放档案资源,那么,以下做法非常方便:

Source. fromFile ("myfile.csv”).getLines.next(

如果你想要关闭档案,那么你想要获得一个空洞的收集,而不是在档案实际上空洞的情况下留下一个错误,那么,你就希望得到一个空洞的收集,而不是一个错误。

val myLine = {
  val src = Source.fromFile("myfile.csv")
  val line = src.getLines.take(1).toList
  src.close
  line
}

如果你把海山限制在标准图书馆,你可以做的最短路。

我认为,所有其他解决办法要么按所有思路阅读,要么只保留第一行,要么不关闭档案。 解决这些问题的办法如下:

val firstLine = {
  val inputFile = Source.fromFile(inputPath)
  val line = inputFile.bufferedReader.readLine
  inputFile.close
  line
}

如果我错的话,我只有一周在Schala的经验对我非常正确。





相关问题
Parse players currently in lobby

I m attempting to write a bash script to parse out the following log file and give me a list of CURRENT players in the room (so ignoring players that left, but including players that may have rejoined)...

How to get instance from string in C#?

Is it possible to get the property of a class from string and then set a value? Example: string s = "label1.text"; string value = "new value"; label1.text = value; <--and some code that makes ...

XML DOM parsing br tag

I need to parse a xml string to obtain the xml DOM, the problem I m facing is with the self closing html tag like <br /> giving me the error of Tag mismatch expected </br>. I m aware this ...

Ruby parser in Java

The project I m doing is written in Java and parsers source code files. (Java src up to now). Now I d like to enable parsing Ruby code as well. Therefore I am looking for a parser in Java that parses ...

Locating specific string and capturing data following it

I built a site a long time ago and now I want to place the data into a database without copying and pasting the 400+ pages that it has grown to so that I can make the site database driven. My site ...

热门标签