Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a Scala Array[Byte] to Java byte[]?

I have an Akka application with actors written in Scala and others in Java. In one case a Scala Actor writes an Array[Byte] and I need to deserialize this from a Java Actor. In this use-case I ultimately need a String representation in Java of the Array[Byte] so that would also solve my problem.

Scala Actor:

val outputStream = new java.io.ByteArrayOutputStream()
val bufferedOutputStream = new java.io.BufferedOutputStream(outputStream, 1024)
val exitCode : Integer = processBuilder #> bufferedOutputStream !
bufferedOutputStream.flush
val content = outputStream.toByteArray // this gives an Array[Byte]
javaActorRef.tell(content, getSelf())

Java Actor:

/**
 * {@inheritDoc}
 */
@Override
public void onReceive(Object object) throws Exception {
    // object has a Scala Array[Byte] how do I convert here to 
    // byte[] or to String?
like image 320
SkyWalker Avatar asked Mar 13 '14 13:03

SkyWalker


People also ask

Can we convert byte array to file in java?

Convert byte[] array to File using Java In order to convert a byte array to a file, we will be using a method named the getBytes() method of String class. Implementation: Convert a String into a byte array and write it in a file.

How do you convert Bytearray?

There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.

How do you create an array of byte arrays in java?

private byte[][] data; // This is idiomatic Java data = new byte[number][]; data[0] = new byte[some_other_number]; data[1] = new byte[yet_another_number]; ... (or in a loop, obviously). Save this answer.

What is Bytearray in java?

The ByteArrayOutputStream class of the java.io package can be used to write an array of output data (in bytes). It extends the OutputStream abstract class. Note: In ByteArrayOutputStream maintains an internal array of bytes to store the data.


1 Answers

Scala's Array[Byte] is already a Java's byte[]. Proof:

object ScalaSide extends Application {
  val a = Array[Byte](1, 2, 3)

  JavaSide.doSmth(a)
}

--

import java.util.Arrays;

public class JavaSide {
    public static void doSmth(Object arr) {
        byte[] b = (byte[]) arr;
        System.out.println(Arrays.toString(b));
    }
} 

Result:

[1, 2, 3]
like image 165
serejja Avatar answered Sep 28 '22 13:09

serejja