Convert string to byte array by encoding - Java java.lang

Java examples for java.lang:String to Byte Array

Description

Convert string to byte array by encoding

Demo Code

import java.io.UnsupportedEncodingException;

public class Main{

    public static void main(String[] argv){
        String text = "java2s.com";
        String encoding = "UTF-8";
        System.out.println(bytesForString(text,encoding));
    }/*  w w w  .  j a v  a 2s .  co m*/
    public static byte[] bytesForString(String text, String encoding) {
   
        if (encoding == null)
            return text.getBytes();
        try {
            return text == null ? null : text.getBytes(encoding);
        } catch (UnsupportedEncodingException e) {
           return null;
        }
    }

}

Related Tutorials