String to byte array,byte array to String in Scala

22 total views, 1 views today

Welcome to Scala series. In this tutorial, you will learn how to convert String to byte array,byte array to String in Scala.

Convert String to byte array in Scala

In some scenarios or use cases, you would be needing to convert your string into an Array of byte for serialization or storage. In this case, you can use the below example to convert String to a byte array.

1. Use str.getBytes() operation to convert your string to array of bytes. This operation used default Charset.

object Test {
  def main(args: Array[String]): Unit = {

    var str: String = "My Scala";
    var stringByte: Array[Byte] = str.getBytes;

    println(stringByte)
  }
}

Output

[B@723279cf

2.Use str.getBytes(Charset) operation to convert your string to array of bytes in different Charset

import java.nio.charset.StandardCharsets

def main(args: Array[String]): Unit = {

    var str: String = "My Scala";
    var stringByte: Array[Byte] = str.getBytes(StandardCharsets.UTF_8);

    println(stringByte.toArray)
}
import java.nio.charset.StandardCharsets

def main(args: Array[String]): Unit = {

    var str: String = "My Scala";
    var stringByte: Array[Byte] = str.getBytes(StandardCharsets.UTF_16);

    println(stringByte.toArray)
}

Convert byte array to String in Scala

1. Using default Charset and new String() operation

object StaticRef {
  def main(args: Array[String]): Unit = {

    var str: String = "My Scala";
    var stringByte: Array[Byte] = str.getBytes();

    println(new String(stringByte))
  }
}

Output

My Scala

2. Using Standard UTF-8 and UTF-16 Charset and new String() operation

import java.nio.charset.StandardCharsets

object StaticRef {
  def main(args: Array[String]): Unit = {

    var str: String = "My Scala";
    var stringByte: Array[Byte] = str.getBytes(StandardCharsets.UTF_8);

    println(new String(stringByte))
  }
}
import java.nio.charset.StandardCharsets

object StaticRef {
  def main(args: Array[String]): Unit = {

    var str: String = "My Scala";
    var stringByte: Array[Byte] = str.getBytes(StandardCharsets.UTF_16);

    println(new String(stringByte))
  }
}

I hope this tutorial  String to byte array,byte array to String in Scala was useful and you were able to understand with a detailed example. Please leave a comment below and give us a thumbs up!.

Tags :

About the Author

Rajasekar

Hey There, My name is Rajasekar and I am the author of this site. I hope you are liking my tutorials and references. Programming and learning new technologies are my passion. The ultimate idea of this site is to share my knowledge(I am still a learner :)) and help you out!. Please spread your words about us (staticreference.com) and give a thumbs up :) Feel free to contact me for any queries!.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.