Steven segal Steven segal - 1 year ago 72
Scala Question

Exporting user input to txt file

I can enter data in the form of "DATA > 11,12,54,34,67,23" and it saves to the txt file in this format;

(DATA > 11,12,54,34,67,23)

However if i try and add another after running this again, this first one is deleted and replaced.
How can i make it so that there are no brackets being saved as my read function does not work with the brackets, and the next one saved goes on the next line instead of replacing the original?

Here is my code

val mapdata3 = readFile("newDataFile.txt")
var mapdata2 = Map()
println ("Data in file " + mapdata3)

// *******************************************************************************************************************
def readFile(filename: String): Map[String, List[Int]] = {
def processInput(lines: Iterator[String]): Map[String, List[Int]] = {
Try {
lines.foldLeft(Map[String, List[Int]]()) { (acc, line) =>

val splitline = line.split(",").map(_.trim).toList
}.getOrElse {
println("Sorry, an exception happened.")
// *****************************************************************************************

print("Enter Data key > ")
val key = readLine()

var result = key.split(";").map(_ split ">") collect { case Array(k, v) => (k, v) } toMap

println ("Data entered into file" + result)

// Writes the newly created stock list to the txt file
val data = result
val file = "newDataFile.txt"
val writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)))
for (x <- data) {
writer.write(x + "\n") // however you want to format it

Answer Source

You need to open the file in append mode. Use this constructor instead:

public FileOutputStream(File file,
                boolean append)
                 throws FileNotFoundException

append - if true, then bytes will be written to the end of the file rather than the beginning

The rest seems fine, you already have a new line at the end of your write.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download