Scala - 将字符串打印到文件的正确方法

Scala - proper way to print a string to file

打印字符串(且仅打印字符串)到文件的正确方法是什么?当我尝试以我所知的标准方式进行操作时,即:

def printToFile(o:Object,n:String) = try{
  val pathToOutput = "..\some\parent\directory\"
  val path = Paths.get(pathToOutput + n)

  val b = new ByteArrayOutputStream()
  val os = new ObjectOutputStream(b)
  os.writeObject(o)

  Files.write(path, b.toByteArray,
    StandardOpenOption.CREATE,
    StandardOpenOption.TRUNCATE_EXISTING)
}catch{
  case _:Exception => println("failed to write")
}

它似乎总是在前面

’ NUL ENQtSTXT

after ENQt 部分似乎有所不同。 (无论我声明 o 一个对象还是一个字符串都没有关系。)

这很烦人,因为我想打印几个 .dot-Strings (Graphviz),然后将生成的 .dot 文件批处理为 .pdf 文件。然而,前面的废话迫使我打开每个 .dot 文件并手动将其删除——这违背了对它们进行批处理的目的。

这与 Scala 无关,这是 Java 标准库的工作方式。当您执行 writeObject 时,您正在编写对象的序列化表示,以及 JVM 可用于重新创建该对象的一堆额外字节。如果您知道该对象是 String,则对其进行强类型化(即,使用 printToFile(o:String,n:String) 并且您可以使用 Files.write(path, o.getBytes, ...。否则您可以使用 o.toString.getBytes.

一般在 JVM 中,如果你想写字符而不是字节,你应该更喜欢 *Writer 而不是 *OutputStream。在这种情况下(假设您有一个要写入的 File 和一个要写入的 String):

val writer = new BufferedWriter(new FileWriter(file))
try {
  writer.write(string)
} finally {
  writer.close()
}

或面向字符的重载 Files.write:

Files.write(path, Collections.singletonList(string), ...)