Scalable Languageor we can say Scalais a JVM based language. Scala is a hybrid functional programming language and object-oriented programming language.  Scala and Java are two of the most important and widely used programming languages.

This article contains about to Create Temporary File using java.io.File and java.nio.file.Filesin Scala.

 Scala Create Temporary File using java.io.File

java.io.File has createTempFile method used to create a temporary file and it accepts two arguments prefix and postfix of file to create a temporary file. It returns a boolean value, If it returns true then it guarantees that The file denoted by the returned abstract pathname did not exist before createTempFile was invoked, and Neither this method nor any of its variants will return the same abstract pathname again in the current invocation of the virtual machine.

import java.io.File

object ScalaCreateTempFile {
  def main (args: Array[String]): Unit = {
    val file = File.createTempFile("pre-",".txt");      // val means final, now file reference can not be change
    print(file.toPath)    // it will print file path
  }
}

Output:

C:\Users\JavaDeveloperZone\AppData\Local\Temp\pre-8848350074072709177.txt

Scala Create Temporary File using java.nio.file.Files

java.nio.file.Files has createTempFile method which accept three arguments prefix of a file, postfix of a file, and optional file attributes. 

It will create an empty file under the temporary-file directory. It will return the path to the newly created file.

import java.nio.file.Files

object ScalaCreateTempFile {
  def main (args: Array[String]): Unit = {
    val path = Files.createTempFile("pre-",".txt");      // val means final, now file reference can not be change
    print(path)    // it will print file path
  }
}

Output:

C:\Users\JavaDeveloperZone\AppData\Local\Temp\pre-8848350074072709177.txt

Conclusion

In this article, we have discussed some basic of Scala programming language and various method of creating a temporary file using java.io.File and java.nio.file.Fileswith examples.

References

Was this post helpful?

Leave a Reply

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