title: Creating a new File in Scala with PrintWriter
body: <p>I have created a function to create a file.
  My goal is to  pass in a json string and return a new File with the contents of the json string passed into it. I am calling this function in another function as:</p>
  
  <pre><code>val jsonFile: File = JsonCreate.getJsonFile(jsonString)
  </code></pre>
  
  <p>So far, the way I have is as follows:
  I create a new file that does not exist and I call it "myJson.json"</p>
  
  <p>I then create a PrintWriter object, with the idea of using this to create my final file. So, I read the contents of the json string, into a StringBuffer, and then over into the PrintWriter. With this done, I hope to have a file myJson.json with the contents of the passed in Json string.</p>
  
  <p>I am not so pleased with the result of my efforts so far. For example, I am not sure if I have used Option the way it is supposed to be used. I am not pleased with the way I am using vars. <br> If I declare a val inside a try, I am not able to access it in the finally. So I go the Java way and put the PrinterWriter Option variable outside.This is a code smell I do not like. <br>
   How can I shorten it and still retain the right try catch and finally, close the resources, etc.</p>
  
  <p>This is my first attempt at writing this function:</p>
  
  <pre><code>import java.io._
  import java.util.Scanner
  
  object JsonCreate{
       def createFile(jsonString: String): File = {
  
          var tmpFile = new File("myJson.json")
          var outFileOpt: Option[PrintWriter] = Some(new PrintWriter(new FileWriter(tmpFile, true)))
  
  
          try {
            //Update: Corrected the value of the Scanner parameter
            val inFile: Scanner = new Scanner(jsonString)
            while(inFile.hasNextLine) {
              val strBuf = new StringBuffer(inFile.nextLine())
              println("Contents of String Buffer is: " + strBuf)
              outFileOpt.get.print(strBuf)
            }
  
          }catch {
            case fnfex: FileNotFoundException =&gt; fnfex.printStackTrace()
            case ioex: IOException =&gt; ioex.printStackTrace()
  
          } finally {
            outFileOpt.get.close()
          }
  
          tmpFile
  
        }
  
  
  }
  </code></pre>