Java Scala读取文件并拆分和修改每一行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21035252/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 06:06:20  来源:igfitidea点击:

Scala read file and split and modify each line

javascalafunctional-programming

提问by macemers

I'm new to Scala. I want to read lines from a text file and split and make changes to each lines and output them.

我是 Scala 的新手。我想从文本文件中读取行并拆分并更改每一行并输出它们。

Here is what I got:

这是我得到的:

 val pre:String = " <value enum=\""
 val mid:String = "\" description=\""
 val sur:String = "\"/>"

 for(line<-Source.fromFile("files/ChargeNames").getLines){
    var array = line.split("\"")
    println(pre+array(1)+mid+array(3)+sur);
 }

It works but in a Object-Oriented programming way rather than a Functional programming way.

它以面向对象的编程方式而不是函数式编程方式工作。

I want to get familiar with Scala so anyone who could change my codes in Functional programming way?

我想熟悉 Scala,以便任何可以以函数式编程方式更改我的代码的人?

Thx.

谢谢。

采纳答案by 1esha

One traversal and no additional memory

一次遍历,无需额外内存

 Source
  .fromFile("files/ChargeNames")
  .getLines
  .map { line =>
    //do stuff with line like
    line.replace('a', 'b')
  }
  .foreach(println)

Or code which is a little bit faster, according to @ziggystar

或者根据@ziggystar 的说法,代码稍微快一点

Source
  .fromFile("files/ChargeNames")
  .getLines
  .foreach { line =>
    //do stuff with line like
    println(line.replace('a', 'b'))
  }

回答by stewSquared

val ans = for (line <- Source.fromFile.getLines) yield (line.replace('a', 'b')
ans foreach println