Java Object to Byte Array getBytes(Object obj)

Here you can find the source of getBytes(Object obj)

Description

get Bytes

License

Apache License

Declaration

public static byte[] getBytes(Object obj) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.io.IOException;

import java.io.ObjectOutputStream;

import java.io.UnsupportedEncodingException;

public class Main {
    public final static String Charset = "utf-8";

    public static byte[] getBytes(Object obj) {
        if (obj == null)
            return null;
        if (obj instanceof String) {
            try {
                return ((String) obj).getBytes(Charset);
            } catch (UnsupportedEncodingException e) {
                return null;
            }/*from  www. j a  v  a 2 s. co  m*/
        }
        java.io.ByteArrayOutputStream a = new java.io.ByteArrayOutputStream();
        try {
            ObjectOutputStream o = new ObjectOutputStream(a);
            o.writeObject(obj);
            o.flush();
            byte[] bytes = a.toByteArray();
            o.close();
            a.close();
            return bytes;
        } catch (IOException e) {
            return null;
        }
    }
}

Related

  1. getBytes(Object o)
  2. getBytes(Object o)
  3. getBytes(Object o)
  4. getBytes(Object obj)
  5. getBytes(Object obj)
  6. getBytes(Object obj)
  7. getBytes(Object obj)