scala 写入文件
Scala:编写文本文件 (Scala: Write text files)
To write text to file in Scala, we have to use the java.io object as it relies on java object for performing some functions.
要在Scala中将文本写入文件,我们必须使用java.io对象,因为它依赖于Java对象来执行某些功能。
In scala, the PrintWriter and FileWriter are employed to perform the write to file operation.
在scala中,使用PrintWriter和FileWriter来执行写文件操作。
Steps involved in writing to file
写入文件涉及的步骤
Here, are some steps that we will follow to write to a file in Scala,
在这里,我们将按照一些步骤将内容写入Scala中的文件,
Create a new PrintWriter / FileWriter object using the fileName.
使用fileName创建一个新的PrintWriter / FileWriter对象。
Use the write() function to write to the file.
使用write()函数写入文件。
Use close method after completing the write operation.
完成写操作后,请使用close方法。
Syntax:
句法:
Writing to a file using PrintWriter,
使用PrintWriter写入文件,
val printWriter_name = new PrintWriter(new File("fileName"))
printWriter_name.write("text")
printWriter_name.close
Writing to a file using FileWriter,
使用FileWriter写入文件,
val file = new File(fileName)
val writer_name = new BufferedWriter(new FileWriter(file))
writer_name.write(text)
writer_name.close()
Example 1:
范例1:
Writing to a file - "includehelp.txt" text - "scala is an amazing programming language." using PrintWriter.
写入文件-“ includehelp.txt”文本-“ scala是一种了不起的编程语言。” 使用PrintWriter。
import java.io._
object MyObject {
def main(args: Array[String]) {
val writer = new PrintWriter(new File("includehelp.txt"))
writer.write("Scala is an amazing programming language")
writer.close()
}
}
Output:
输出:
//The program will write content to the file.
Explanation:
说明:
In the above code, we have created the writer that will be used to write to file using the write() method.
在上面的代码中,我们创建了writer ,将使用write()方法将其写入文件。
Example 2:
范例2:
We will write to the file "text.txt", the text "I love programming Scala" using FileWriter.
我们将使用FileWriter将文件“ text.txt”写入文本“ I love programming Scala”。
import java.io._
object MyObject {
def main(args: Array[String]) {
val writeFile = new File("text.txt")
val inputString = "I love programming in Scala"
val writer = new BufferedWriter(new FileWriter(writeFile))
writer.write(inputString)
writer.close()
}
}
Output:
输出:
// This will write the content of the inputString to the file named "text.txt".
Explanation:
说明:
In the above code, we have used the FileWriter to write to the file name "text.txt", the contents to be written are given by inputString and the method write() is employed to perform the writing task.
在上面的代码中,我们使用FileWriter写入文件名“ text.txt”,要写入的内容由inputString给出,并使用write()方法执行写入任务。
翻译自: https://www.includehelp.com/scala/how-to-write-in-a-file-in-scala.aspx
scala 写入文件