Creating a new File in Scala with PrintWriter -


i have created function create file. goal pass in json string , return new file contents of json string passed it. calling function in function as:

val jsonfile: file = jsoncreate.getjsonfile(jsonstring) 

so far, way have follows: create new file not exist , call "myjson.json"

i create printwriter object, idea of using create final file. so, read contents of json string, stringbuffer, , on printwriter. done, hope have file myjson.json contents of passed in json string.

i not pleased result of efforts far. example, not sure if have used option way supposed used. not pleased way using vars.
if declare val inside try, not able access in finally. go java way , put printerwriter option variable outside.this code smell not like.
how can shorten , still retain right try catch , finally, close resources, etc.

this first attempt @ writing function:

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 value of 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 => fnfex.printstacktrace()           case ioex: ioexception => ioex.printstacktrace()          } {           outfileopt.get.close()         }          tmpfile        }   } 

there no need store file in option. using option.get sign you're doing wrong, because assume option set.

then if have string, there no reason why want scan it, write buffer etc. write directly file, using example fileoutputstream.

intercepting exceptions print them out not practice. let them propagate caller.

import java.io.{file, fileoutputstream}  def writetextfile(f:file, contents: string, encoding: string = "utf-8"): unit = {   val fos = new fileoutputstream(f)   try {     fos.write(contents.getbytes(encoding))   } {     fos.close()   } } 

Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -