1

I would like to use scala.sys.process to send a DOT description of a graph to dot and retrieve the conversion to a binary image.

val process = "dot -T" + format
val inputStream = new ByteArrayInputStream(dot.getBytes("UTF-8"))
process #< inputStream !!

This would work fine but !! returns a String, not a Array[Byte]. How can I get the response in bytes instead of a string? I don't think I can use the string as an intermediate representation because the binary data will not describe a valid string.

2
  • Write the dot to a file and read that file from Scala? Apr 12, 2013 at 15:21
  • That would work, but I'd hope there's a way to avoid the File io. Or is there a complication here I'm ignoring?
    – schmmd
    Apr 12, 2013 at 15:26

2 Answers 2

1

If you really want to avoid file IO and you have access to the base64 command-line program under Linux (or an equivalent), you can

val process = Seq("bash","-c","dot -T" + format + " | base64")
val inputStream = new ByteArrayInputStream(dot.getBytes("UTF-8"))
javax.xml.bind.DatatypeConverter.parseBase64Binary(process #< inputStream !!)

to get an array of bytes out.

You can also provide your own ProcessIO that uses the binary-data methods on input/output streams, but that's a lot more work. If base64 is too slow it might be worth it, though. (I expect that dot itself would be the bottleneck, but I'm not sure what you're sending it.)

1

Scala Process IO is neat, but I always find it hard to figure out how to do what I want. Hopefully this example will be helpful to others. What I wanted was quite easy once I found the right voodoo. Here is a function that takes parameters to dot and then runs the process, piping in an InputStream and piping out an OutputStream.

  def dotbin(format: String)(dot: String): Array[Byte] = {
    val process = "dot -T" + format
    val bos = new ByteArrayOutputStream()
    val exitCode = process #< new ByteArrayInputStream(dot.getBytes) #> bos !< ProcessLogger(s => ())
    if (exitCode == 0) {
      bos.toByteArray()
    }
    else {
      throw new RuntimeException("Nonzero exit value (" + exitCode + ") for '" + process + "' with: " + dot)
    }
  }

It's clean an succinct once you find the right symbols. Please note that in 2.10 you don't need to supply a ProcessLogger for !<.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.