简体   繁体   English

如何使用 scala 读取和更改文件中行的 position

[英]How to Read and Change position of lines in a file using scala

I have a file, lets say file1:我有一个文件,比如说file1:

A
B
C
D
E

I have to read this file and want to move 1st and 2nd line from the file to 3rd and 4th line in a file, like:我必须阅读此文件并希望将文件中的第 1 行和第 2 行移动到文件中的第 3 和第 4 行,例如:

C
D
A
B
E

Getlines function can get the lines and probably print it. Getlines function 可以获得这些线条并可能打印出来。 But how to change position of lines in a file using Scala?但是如何使用 Scala 更改文件中的行 position?

Let's say you can't, or just don't want to, read the entire file into memory.假设您不能或只是不想将整个文件读入 memory。 Or, on the other hand, what if the file has fewer than 4 lines?或者,另一方面,如果文件少于 4 行怎么办? Can the swapping still be done safely?交换仍然可以安全地进行吗?

import java.nio.file.{Files, Paths}

util.Using.Manager { use =>  //Scala 2.13
  val input  = use(io.Source.fromFile("inFile.txt"))
  val output = use(Files.newBufferedWriter(Paths.get("outFile.txt")))

  val itr = input.getLines()
  val linesAB = Seq.fill(2)(util.Try(itr.next()))
  val linesCD = Seq.fill(2)(util.Try(itr.next()))
  linesCD.foreach(_.foreach(s => output.write(s + "\n")))
  linesAB.foreach(_.foreach(s => output.write(s + "\n")))
  while (itr.hasNext) output.write(itr.next() + "\n")

}.fold(println,identity)  //report failure

result:结果:

~> head *File.txt  # a 3-line file
==> inFile.txt <==
A
B
C

==> outFile.txt <==
C
A
B

Here is a pragmatic solution:这是一个务实的解决方案:

  val newList =Source.fromFile("file.txt").getLines().toList match {
    case a::b::c::d::rest => c::d::a::b::rest // reorganize your list
    case other => other // don't do anything if the List has not at least 4 elements
  }
  // persist newList

Use the Pattern Matching of the List type.使用List类型的模式匹配

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM