Write String to File in Scala

In this example, we will show simple example about, How to write string to file in scala. The program has been tested and shared in the post.

Example Code

import java.io.File;
import java.io.FileWriter;
import java.util.Scanner;
object WriteFileExample {
def writeFile(fileName: String, content: String) {
if(fileName != null && !fileName.isEmpty()) {
var file = new File(fileName);
var fileWriter = new FileWriter(file);
fileWriter.write(content);
fileWriter.close();
}
}
def main(args: Array[String]) {
var scanner = new Scanner(System.in);
var fileName = "abc.txt";
println("Enter the Content");
var content = scanner.nextLine();
writeFile(fileName, content);
println("The content has been written to file successfully...");
}
}

Output

Enter the Content
This is Dinesh Krishnan
The content has been written to file successfully…

Tags:

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *