-1

I'm new to Scala & Java, trying to write .properties file using it but its giving errors:

Ref: https://www.roseindia.net/java/example/java/core/write-properties-file-in-java.shtml

Following is code:

import java.io.File
import java.io.FileWriter
import java.io.BufferedWriter
import java.io.PrintWriter
import java.io.FileInputStream
import java.io.FileOutputStream
import java.util.Properties;


for ((k,v) <- jsonData.get.asInstanceOf[Map[String,String]]){
        var gdfileWriter : Writer = null;
        try{                    

          var prop : Properties = null;    
      prop = new Properties();

      var file : File = null;          
      file = new File(gdDestFileNameWithPath);

      var fos : FileOutputStream = null;
      fos = new FileOutputStream(file);

      prop.setProperty("database", "localhost");
      prop.setProperty("userName", "Naulej");
      prop.setProperty("Password", "naulej");
      prop.store(fos, "");

      fos.close();

//        gdfileWriter = new FileWriter(gdDestFileNameWithPath);
//        dfileWriter.write("");
//        gdfileWriter.append(gdJsonContent);
//        gdfileWriter.close();          
        } finally{
          try{gdfileWriter.close();}catch {
            case t: Throwable => t.printStackTrace() // TODO: handle error
          }
        }         
      }

file.setProperty("Password", "naulej"); This line giving me syntax error in eclipse i.e. value setProperty is not a member of java.io.File

Any help would be appreciated.

J.K.A.
  • 7,272
  • 25
  • 94
  • 163

1 Answers1

1

There are several things here. At first you're write more or less java which is okay but then you should probably put the code into a java file. Anyway using java from scala is intended and usually no problem. Just look out for exceptions and null.

Regarding scala here is my (probably incomplete) list:

  1. Semicolons are optional and usually omitted in scala code.
  2. Instead of using try ... catch you might want to take a look at scala.util.Try.
  3. See if you can initialise "expensive" components (IO) outside of a loop.
  4. Try to avoid null. ;-)
  5. If you really need variables (var) that may be "uninitialised" take a look at the Option type that can be used for that.

Here is an example:

import java.io.{ File, FileOutputStream }
import java.util.Properties

Try {
  val p  = new Properties
  val f  = new File(...)
  val fs = new FileOutputStream(f)

  // Set your properties and save them...

  p // Return the created properties in the end
}

This will result in a Try[Properties] that you can use to check if any exception occured.

jan0sch
  • 62
  • 6