Showing posts with label copy file. Show all posts
Showing posts with label copy file. Show all posts

Monday, August 10, 2009

Calling Java APIs

Calling Java APIs from Scala is completely seamless. I will demonstrate this functionality by copying data from a URL to a file and then making a copy of that file.

Important Note: Scala 2.8 is getting a redesigned API for accessing files and streams based on JSR-203 New NIO. It is quite nice to use. For example File("/tmp") / "dir" / "dir2" will create a file to /\
tmp/dir/dir2. That is just the most basic of what you can expect. I will do a couple topics on that when it gets closer to being finalized.
  1. scala>import java.net._
  2. import java.net._
  3. scala>import scala.io._
  4. import scala.io._
  5. scala>import java.io.{File, FileWriter}
  6. import java.io.{File, FileWriter}
  7. scala>val in = Source.fromURL("http://www.google.com")
  8. in: scala.io.Source = non-empty iterator
  9. scala>// Until scala 2.8 we have to use the standard java streams and idioms
  10. scala>val out = new FileWriter("/tmp/daily-scala")
  11. out: java.io.FileWriter = java.io.FileWriter@71d0e17a
  12. scala>try {
  13.     | out.write( in.getLines.mkString("\n") )
  14.     | }finally{
  15.     | out.close
  16.     | }
  17. scala>// now lets copy the file
  18. scala>val copy = new FileWriter("/tmp/copy")
  19. copy: java.io.FileWriter = java.io.FileWriter@7bfd25ce
  20. scala>try {
  21.     | copy.write( Source.fromFile("/tmp/daily-scala").getLines.mkString("\n") )
  22.     | } finally {copy.close}
  23. scala>val copy2 = new FileWriter("/tmp/copy2")
  24. copy2: java.io.FileWriter = java.io.FileWriter@7bfd25ce
  25. // You can reuse a source if you reset it
  26. scala>try {
  27.     | copy2.write( in.reset.getLines.mkString("\n") )
  28.     | } finally {copy2.close}
  29. // Change all 'e' to upper case.  We could write this to a file if we desired
  30. scala> in.reset.getLines.mkString("\n").map( c => if (c == 'e') c.toUpperCase else c).mkString("")
  31. res9: String = This is thE dEmo filE