Skip to content

Instantly share code, notes, and snippets.

@satendrakumar
Last active August 26, 2017 06:49
Show Gist options
  • Save satendrakumar/b52532c5338451a090c5abb2c2d76cd2 to your computer and use it in GitHub Desktop.
Save satendrakumar/b52532c5338451a090c5abb2c2d76cd2 to your computer and use it in GitHub Desktop.
while loop alternatives in Scala
import java.io._
object Loop1 extends App {
//Java way
val inputStream: BufferedInputStream = new BufferedInputStream(new FileInputStream("input.csv"))
val outputStream = new BufferedOutputStream(new FileOutputStream("output.csv"))
val buffer = new Array[Byte](32 * 1024)
var bytesRead: Int = inputStream.read(buffer)
while (bytesRead > 0) {
println("writing.......")
outputStream.write(buffer, 0, bytesRead)
outputStream.flush()
bytesRead = inputStream.read(buffer)
}
inputStream.close()
outputStream.close()
}
object Loop2 extends App {
//Functional way
val inputStream: BufferedInputStream = new BufferedInputStream(new FileInputStream("input.csv"))
val outputStream = new BufferedOutputStream(new FileOutputStream("output.csv"))
val buffer = new Array[Byte](32 * 1024)
Stream.continually(inputStream.read(buffer)).takeWhile(_ > 0).foreach { bytesRead =>
println("writing.......")
outputStream.write(buffer, 0, bytesRead)
outputStream.flush()
}
inputStream.close()
outputStream.close()
}
object Loop3 extends App {
//Functional way but better than 2
val inputStream: BufferedInputStream = new BufferedInputStream(new FileInputStream("input.csv"))
val outputStream = new BufferedOutputStream(new FileOutputStream("output.csv"))
val buffer = new Array[Byte](32 * 1024)
Iterator.continually(inputStream.read(buffer)).takeWhile(_ > 0).foreach { bytesRead =>
println("writing.......")
outputStream.write(buffer, 0, bytesRead)
outputStream.flush()
}
inputStream.close()
outputStream.close()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment