How often do you need to write or read files? This is a pretty common task in any more or less non-trivial project. Image upload process, CSV or XML parsing, XLS report generation etc. All these operations imply input or output processing. So I’m going to make an overview of the most powerful library for working with files in Scala.
Here is a list of operations which I want to cover:
- File creation and removal
- File writing and reading
- File comparison
- Zipping and unzipping
import better.files._
import better.files.File._
object Worksheet_WithoutUsingImport extends App{
// How to Create a File or Directory (Or Handle If It Doesn't Exist)
//************Section1********************************************************
//file val Newfile: File = "C:/Users/admin/Desktop/JSON_FOLDER/DSS1.txt"
.toFile.createIfNotExists()
//Directory val directory:File = "C:/Users/admin/Desktop/JSON_FOLDER/Divyanshu"
.toFile.createIfNotExists(true)
//creation of a folder with an extra path?
val directory1:File = "C:/Users/admin/Desktop/JSON_FOLDER/Divyanshu1/Shekhar/Singh"
.toFile.createIfNotExists(true,true)
//**************Section2***************************************************************
//Writing content to file
val WriteFile = (root/"C:/Users/admin/Desktop/JSON_FOLDER/DSS1.txt")
.createIfNotExists()
.overwrite("")
.appendLines("Hi How Are You","i'm doing good","Welcome!","Hello")
//************Section3********************************************************************
//Read File content
println(WriteFile.contentAsString)
//OR
val simpleFile = (root/ "C:/Users/admin/Desktop/JSON_FOLDER/DSS2.txt")
.overwrite("")
.appendLines("Hi How Are You", "i'm doing good", "Welcome!")
simpleFile.lines.map(line => println(s"DSS $line SSD"))
//Note: // Use == :when you want to compare two files or directories by path.
// Use === when you want to check equality of two files or folders by content.
if (simpleFile == WriteFile){
println(s" File comparison is done")
}
else println("Not equal")
//Delete Files and Directories
val FileDelete = (root/"C:/Users/admin/Desktop/JSON_FOLDER/DSS3.txt" )
.createIfNotExists()
if (FileDelete.exists)
FileDelete.delete()
//*******************Section4**************************************************
//Zip and Unzip Files and Directories
val ZipFiles = (root / "C:/Users/admin/Desktop/JSON_FOLDER/DSS2.txt")
ZipFiles.zipTo(root / "C:/Users/admin/Desktop/JSON_FOLDER/Archive.zip")
//Note:
Use This Library in build.sbt:
libraryDependencies += "com.github.pathikrit" %% "better-files" % "3.9.1"
}
No comments:
Post a Comment