1

I have the following code where I am reading a file and replacing any occurences of "*.tar.gz" file with the new file name provided. Everything works fine and I can see the replaced changes in the console however I am not being able to write a new file with all the changes.

def modifyFile(newFileName: String, filename: String) = {
    Source.fromFile(filename).getLines.foreach { line =>
      println(line.replaceAll(".+\\.tar\\.gz", newFileName.concat(".tar.gz")))
    }
  }
}
summerNight
  • 1,446
  • 3
  • 25
  • 52

1 Answers1

2

You forgot to write your modified lines into the new file:

def modifyFile(newFileName: String, sourceFilePath: String, targetFilePath:String) {
  scala.tools.nsc.io.File(targetFilePath).printlnAll(
    Source.fromFile(sourceFilePath).getLines().map { 
       _.replaceAll(".+\\.tar\\.gz", newFileName.concat(".tar.gz"))
    }.toSeq:_*)
}

Please note that this approach is not the most efficient in terms of performance, as the content of source file is read fully to memory, processed and then written back. More efficient approach will be more verbose and will include java's FileReader/FileWriter.

Upd

As rightfully pointed in comments you have to chose suitable way to write result to file depending on what tools and dependencies you have.

Community
  • 1
  • 1
Aivean
  • 10,692
  • 25
  • 39
  • 1
    It would be worth adding that this approach needs a dependency to scala-compiler.jar. Another simple approach (without additional dependencies) would be to use the java.nio.file classes (if running on JRE 7+). – Cyäegha Jul 31 '15 at 21:58