0
我可以以「DATA> 11,12,54,34,67,23」的形式輸入數據,並以此格式保存到txt文件中;將用戶輸入導出到txt文件
(DATA> 11,12,54,34,67,23)
但是,如果我嘗試並再次運行此之後添加另一個,這第一個被刪除並替換。 我怎樣才能讓它沒有括號被保存,因爲我的閱讀功能不支持括號,下一個保存在下一行而不是替換原來的?
這裏是我的代碼
val mapdata3 = readFile("newDataFile.txt")
var mapdata2 = Map()
println ("Data in file " + mapdata3)
// *******************************************************************************************************************
// UTILITY FUNCTIONS
//GETS THE DATA FROM THE DATA.TXT
def readFile(filename: String): Map[String, List[Int]] = {
processInput(Source.fromFile(filename).getLines)
}
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
acc.updated(splitline.head, splitline.tail.map(_.toInt))
}
}.getOrElse {
println("Sorry, an exception happened.")
Map()
}
}
// *****************************************************************************************
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
}
writer.close()
在Writer val的末尾,我還沒有調用文件輸出流嗎? 「(new FileOutputStream(file)」@yǝsʞǝlA –
我的意思是:new FileOutputStream(file,true) –