Scala:在一条语句中将字符串写入文件
对于在Scala中读取文件,有Scala:在一条语句中将字符串写入文件,scala,scala-2.9,Scala,Scala 2.9,对于在Scala中读取文件,有 Source.fromFile("file.txt").mkString 是否有一种等效且简洁的方法将字符串写入文件 大多数语言都支持这样的功能。我最喜欢的是Groovy: def f = new File("file.txt") // Read def s = f.text // Write f.text = "file contents" 我想将代码用于从一行到一小页代码的程序。必须使用自己的图书馆在这里没有意义。我希望现代语言能让我方便地向文件中写入内容
Source.fromFile("file.txt").mkString
是否有一种等效且简洁的方法将字符串写入文件
大多数语言都支持这样的功能。我最喜欢的是Groovy:
def f = new File("file.txt")
// Read
def s = f.text
// Write
f.text = "file contents"
我想将代码用于从一行到一小页代码的程序。必须使用自己的图书馆在这里没有意义。我希望现代语言能让我方便地向文件中写入内容
也有类似的帖子,但它们没有回答我的确切问题,或者只关注较旧的Scala版本
例如:
import java.io._
import scala.io._
class RichFile( file: File ) {
def text = Source.fromFile( file )(Codec.UTF8).mkString
def text_=( s: String ) {
val out = new PrintWriter( file , "UTF-8")
try{ out.print( s ) }
finally{ out.close }
}
}
object RichFile {
implicit def enrichFile( file: File ) = new RichFile( file )
}
它将按预期工作:
scala> import RichFile.enrichFile
import RichFile.enrichFile
scala> val f = new File("/tmp/example.txt")
f: java.io.File = /tmp/example.txt
scala> f.text = "hello world"
scala> f.text
res1: String =
"hello world
你可以很容易地使用。查看函数
writeStringToFile
。我们在项目中使用此库。下面是一个使用reflect.io.file的简明单行程序,它适用于Scala 2.12:
reflect.io.File("filename").writeAll("hello world")
或者,如果您想使用Java库,可以执行以下操作:
Some(new PrintWriter("filename")).foreach{p => p.write("hello world"); p.close}
您可以混合使用Java和Scala库来实现这一点。您将完全控制字符编码。但不幸的是,文件句柄无法正确关闭
scala> import java.io.ByteArrayInputStream
import java.io.ByteArrayInputStream
scala> import java.io.FileOutputStream
import java.io.FileOutputStream
scala> BasicIO.transferFully(new ByteArrayInputStream("test".getBytes("UTF-8")), new FileOutputStream("test.txt"))
还有一种是这种格式,它既简洁又漂亮地编写了底层库(请参阅源代码):
更新:我创建了一个更有效的解决方案,我在这里对此进行了详细阐述: 我发现自己越来越多地在Scala IDE for Eclipse中使用Scala工作表(我相信IntelliJ IDEA中也有类似的东西)。无论如何,当我得到“输出超出截止限制”消息时,我需要能够使用一行程序输出一些内容。如果我正在做任何有意义的事情,尤其是在Scala集合中 我在每个新的Scala工作表的顶部插入了一行代码来简化这个过程(因此,我不必为了一个非常简单的需要而进行整个外部库导入练习)。如果你是一个固执己见的人,并注意到它在技术上是两行的,这只是为了让它在这个论坛上更具可读性。这是我的Scala工作表中的一行
def printToFile(content: String, location: String = "C:/Users/jtdoe/Desktop/WorkSheet.txt") =
Some(new java.io.PrintWriter(location)).foreach{f => try{f.write(content)}finally{f.close}}
用法很简单:
printToFile("A fancy test string\ncontaining newlines\nOMG!\n")
printToFile("A fancy test string\ncontaining newlines\nOMG!\n", "C:/Users/jtdoe/Desktop/WorkSheet.txt")
这允许我选择提供文件名,如果我希望在默认值之外有其他文件(每次调用该方法时都会完全覆盖该文件)
因此,第二种用法很简单:
printToFile("A fancy test string\ncontaining newlines\nOMG!\n")
printToFile("A fancy test string\ncontaining newlines\nOMG!\n", "C:/Users/jtdoe/Desktop/WorkSheet.txt")
享受吧 我想这已经足够简洁了:
scala> import java.io._
import java.io._
scala> val w = new BufferedWriter(new FileWriter("output.txt"))
w: java.io.BufferedWriter = java.io.BufferedWriter@44ba4f
scala> w.write("Alice\r\nBob\r\nCharlie\r\n")
scala> w.close()
奇怪的是,没有人建议NIO.2操作(从Java7开始提供): 我认为这是迄今为止最简单、最简单、最惯用的方法,它不需要任何依赖项,而无需Java本身。一句简洁的话:
import java.io.PrintWriter
new PrintWriter("filename") { write("file contents"); close }
我写的一个微型图书馆:
或
file我知道这不是一行,但就我所知,它解决了安全问题
// This possibly creates a FileWriter, but maybe not
val writer = Try(new FileWriter(new File("filename")))
// If it did, we use it to write the data and return it again
// If it didn't we skip the map and print the exception and return the original, just in-case it was actually .write() that failed
// Then we close the file
writer.map(w => {w.write("data"); w}).recoverWith{case e => {e.printStackTrace(); writer}}.map(_.close)
如果您不关心异常处理,那么您可以编写
writer.map(w => {w.writer("data"); w}).recoverWith{case _ => writer}.map(_.close)
通过分号的魔力,你可以做任何你喜欢的一行
import java.io.PrintWriter
import java.nio.file.Files
import java.nio.file.Paths
import java.nio.charset.StandardCharsets
import java.nio.file.StandardOpenOption
val outfile = java.io.File.createTempFile("", "").getPath
val outstream = new PrintWriter(Files.newBufferedWriter(Paths.get(outfile)
, StandardCharsets.UTF_8
, StandardOpenOption.WRITE)); outstream.println("content"); outstream.flush(); outstream.close()
使用图书馆。语法非常简单,但库的宽度几乎与在bash这样的shell脚本语言中尝试执行这样的任务所期望的一样宽
在我链接到的页面上,它显示了可以对库执行的许多操作,但要回答这个问题,这是一个写入文件的示例
import ammonite.ops._
write(pwd/'"file.txt", "file contents")
是写入文件的最佳现代方式
下面介绍如何将“hello”写入文件.txt
文件
os.write(os.pwd/"file.txt", "hello")
os lib隐藏了Java的丑陋和复杂性(它在引擎盖下使用Java lib,因此性能也一样)。有关使用lib的更多信息,请参阅。这是一款现代、安全的单行程序:
java.nio.file.Files.write(java.nio.file.Paths.get("/tmp/output.txt"), "Hello world".getBytes());
nio是JDK 9+默认附带的现代IO库,因此不需要导入或依赖项。请参阅问题。我同意评分最高的答案——最好有自己的个人图书馆。对于这种情况,我不同意必须编写自己的个人图书馆。通常,当你写一些小程序来做一些特别的事情时(也许我只想把它写成一个单页scala脚本,或者只是在REPL中)。然后访问个人库就成了一件痛苦的事情。基本上,scala 2.9在这一点上似乎没有什么内容。我不知道该如何回答这个问题。如果在Scala源代码中搜索java.io,将不会找到太多实例,输出操作(尤其是PrintWriter)的实例更少。所以,在Scala IO库成为Scala的正式部分之前,我们必须使用纯Java,如paradigmatic所示。是的,prob还需要一个与jdk7 IO改进兼容的Scala IO。它在REPL中对我不起作用。没有错误消息,但是如果我查看/tmp/example.txt,没有@user unknown,很抱歉遗漏了“!”在命令结束时,现在修复。太棒了!既然成功了,我想知道为什么。什么是#>
,什么是代码>执行?此解决方案不可移植!仅适用于*nix系统。这不适用于写入任意字符串。它只适用于可以作为参数传递给命令行echo
工具的短字符串。我也一直在使用它。如果您仔细阅读了这个问题,我已经知道了为什么我不想使用库。如果不使用库,我已经创建了一个解决方案,它可以处理读/写过程中的异常,并且能够在Java库提供的微小缓冲区默认值之外进行缓冲:+1非常有效。Some
/foreach
组合有点时髦,但它的好处是没有try/catch/finally。如果写入操作引发异常,如果您计划从异常中恢复并再次读取/写入该文件,则可能需要关闭该文件。幸运的是,scala也提供了一行程序来实现这一点。不建议这样做,因为scala.tools.nsc.io包不是公共API的一部分,而是由编译器使用的。Some
/foreachimport ammonite.ops._
write(pwd/'"file.txt", "file contents")
os.write(os.pwd/"file.txt", "hello")
java.nio.file.Files.write(java.nio.file.Paths.get("/tmp/output.txt"), "Hello world".getBytes());