user978080
user978080

Reputation:

Change the contents of a file in scala

I've seen this question but I'm not completely sure I can achieve what I want with the answer that was provided.

Note that this is just an experience to study Scala. The example that I'll provide you may not make sense.

I want to open my ~/.subversion/servers file and if I spot a line that has the word "proxy" I want comment it (basically I just want to prepend the character "#"). Every other line must be left as is.

So, this file:

Line 1
Line 2
http-proxy-host = defaultproxy.whatever.com
Line 3

would become:

Line 1
Line 2
# http-proxy-host = defaultproxy.whatever.com
Line 3

I was able to read the file, spot the lines I want to change and print them. Here's what I've done so far:

val fileToFilter = new File(filePath)

io.Source.fromFile(fileToFilter)
  .getLines
  .filter( line => !line.startsWith("#"))
  .filter( line => line.toLowerCase().contains("proxy") )
  .map( line => "#" + line )
  .foreach( line => println( line ) )

I missing two things:

  1. How to save the changes I've done to the file (can I do it directly, or do I need to copy the changes to a temp file and then replace the "servers" file with that temp file?)
  2. How can I apply the "map" conditionally (if I spot the word "proxy", I prepend the "#", otherwise I leave the line as is).

Is this possible? Am I even following the right approach to solve this problem?

Thank you very much.

Upvotes: 5

Views: 6307

Answers (2)

WestCoastProjects
WestCoastProjects

Reputation: 63062

There is no "replace" file method in stock scala libraries: so you would open the file (as you are showing), make the changes, and then save it back (also various ways to do this) to the same path.

AFA Updating certain lines to # if they have proxy:

.map line { case l if l.contains("proxy") => s"# $l"
              case l => l
       }

Upvotes: 0

tuxdna
tuxdna

Reputation: 8487

  1. Save to a different file and rename it back to original one.
  2. Use if-else

This should work:

import java.io.File
import java.io.PrintWriter
import scala.io.Source

val f1 = "svn.txt"  // Original File
val f2 = new File("/tmp/abc.txt") // Temporary File
val w = new PrintWriter(f2)
Source.fromFile(f1).getLines
  .map { x => if(x.contains("proxy")) s"# $x" else x }
  .foreach(x => w.println(x))
w.close()
f2.renameTo(f1)

Upvotes: 7

Related Questions