将scala中生成的数据写入文本文件

时间:2015-03-10 17:01:16

标签: scala output

我希望有人可以提供帮助,我是scala的新手,我在将输出写入文本文件时遇到了一些问题。

我有一个数据表,我已经编写了一些代码,一次只读一行,做我想做的事,现在我需要把它写成文本文件。< / p>

例如,我有以下数据类型表

姓名,日期,goX,goY,stopX,stopY

1,12 / 01 / 01,1166,2299,3300,4477

我的代码,取goX和goY的第一个字符并创建一个新数字,在本例中为1.2,对stopX和stopY也是如此,所以在这种情况下你会得到3.4

我想在文本文件中获得的内容基本上如下:

去,停止

1.2,3.4

我想让它经历数百行,直到我在文本文件中有一长串的开启和关闭。

我目前的代码如下,这几乎肯定不是最优雅的解决方案,但它是我的第一个scala / java代码:

import scala.io.Source

object FT2 extends App {
for(line<-Source.fromFile("C://Users//Data.csv").getLines){

var array = line.split(",")
val gox = (array(2));
val xStringGo = gox.toString
val goX =xStringGo.dropRight(1|2)
val goy = (array(3));
val yStringGo = goy.toString
val goY = yStringGo.dropRight(1|2)
val goXY = goX+"."+goY

val stopx = (array(4));
val xStringStop = stopx.toString
val stopX =xStringStop.dropRight(1|2)
val stopy = (array(3));
val yStringStop = stopy.toString
val stopY = yStringStop.dropRight(1|2)
val stopXY = stopX+"."+stopY

val GoStop = List(goXY,stopXY)
//This is where I want to print GoStop to a text file
}

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:9)

这应该这样做:

import java.io._

val data = List("everything", "you", "want", "to", "write", "to", "the", "file")

val file = "whatever.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()

但是你可以通过创建一个自动关闭东西的方法来使它更好一些:

def using[T <: Closeable, R](resource: T)(block: T => R): R = {
  try { block(resource) }
  finally { resource.close() }
}

using(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)))) { 
  writer =>
    for (x <- data) {
      writer.write(x + "\n")  // however you want to format it
    }
}

所以:

using(new BufferedWriter(new OutputStreamWriter(new FileOutputStream("output.txt")))) { 
  writer =>
    for(line <- io.Source.fromFile("input.txt").getLines) {
      writer.write(line + "\n")  // however you want to format it
    }
}