Binary Data
From mi-linux
Jump to navigationJump to search
This is a collection of hints about how to use the Scala and Java APIs to perform simple operations, of the sort you might need to use to complete the portfolio exercises.
Binary data, rather than strings, characters, and so on, is usually represented in Java as arrays of bytes, called byte[] in Java and Array[Byte] in Scala. Being able to convert binary data to and from Strings, sending both sorts of data down sockets is useful things to know about.
How to convert a String to an Array[Byte]
val mybytes = "I love Scala programming!".getBytes()
Sending Strings and binary data through sockets, or writing them to files
If you are using a Java DataOutputStream (as you saw in the lectures) you can send a String to a DataOutputStream like this:
val out = new DataOutputStream(socket.getOutputStream()) out.writeBytes("Hello socket world!")
and binary data like this:
val out = new DataOutputStream(socket.getOutputStream()) out.write(mybytearray)
How to read in a file as a String
val filedata = scala.io.Source.fromFile("file.txt").mkString()
How to read in a file as binary data
The Scala API for dealing with IO is not very mature, so it's easier here to use the Java API:
/** Get the contents of a give file, as a byte array. * * We use the Java classes here, a the Scala ones are a bit of a hack. * */ def getFileContents(filename : String) : Array[Byte] = { val file = new File(filename) val fis = new FileInputStream(file) val flength : Int = file.length.asInstanceOf[Int] var bytearray = new Array[Byte](flength) fis.read(bytearray) return bytearray }