如何在文件而不是println中保存值?

时间:2019-09-05 20:42:34

标签: scala apache-spark normalization

我想将值保存到txtfile中而不是println中。

val movieMatrix = new RowMatrix(movieVectors) 
 val movieMatrixSummary =movieMatrix.computeColumnSummaryStatistics() 

val userMatrix = new RowMatrix(userVectors) 
val userMatrixSummary = userMatrix.computeColumnSummaryStatistics()
println("Movie factors mean: " + movieMatrixSummary.mean)
println("Movie factors variance: " + movieMatrixSummary.variance) 
println("User factors mean: " + userMatrixSummary.mean) 
println("User factors variance: " + userMatrixSummary.variance)

如何保存值?

1 个答案:

答案 0 :(得分:1)

您可以使用Java PrintWriterFileWriter将值写入文本文件。

// PrintWriter
import java.io._
val pw = new PrintWriter(new File("summary.txt" ))
pw.write("Movie factors mean: " + movieMatrixSummary.mean + "\n")
pw.close

// FileWriter
val file = new File(filepath)
val bw = new BufferedWriter(new FileWriter(file))
bw.write("Movie factors mean: " + movieMatrixSummary.mean + "\n")
bw.close()

通常最好使用FileWriter,因为它会抛出IOExceptions,而PrintWriter不会抛出异常,而是设置可以检查的布尔标志。