Android Object Serialization objectToString(Object o)

Here you can find the source of objectToString(Object o)

Description

object To String

Declaration

public static String objectToString(Object o) 

Method Source Code

//package com.java2s;

import java.io.BufferedOutputStream;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import java.io.ObjectOutputStream;

public class Main {
    public static String objectToString(Object o) {
        if (o == null) {
            return null;
        }//from   www .java  2  s .c om

        ByteArrayOutputStream baos = new ByteArrayOutputStream(32000);

        try {
            ObjectOutputStream os = new ObjectOutputStream(
                    new BufferedOutputStream(baos));
            os.flush();
            os.writeObject(o);
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return encode(baos.toByteArray());
    }

    public static String encode(byte raw[]) {
        StringBuffer encoded = new StringBuffer();

        for (int i = 0; i < raw.length; i += 3) {
            encoded.append(encodeBlock(raw, i));
        }

        return encoded.toString();
    }

    public static String encode(String s) {
        return encode(s.getBytes());
    }

    protected static char[] encodeBlock(byte raw[], int offset) {
        int block = 0;
        int slack = raw.length - offset - 1;
        int end = slack < 2 ? slack : 2;

        for (int i = 0; i <= end; i++) {
            byte b = raw[offset + i];

            int neuter = b >= 0 ? ((int) (b)) : b + 256;
            block += neuter << 8 * (2 - i);
        }

        char base64[] = new char[4];

        for (int i = 0; i < 4; i++) {
            int sixbit = block >>> 6 * (3 - i) & 0x3f;
            base64[i] = getChar(sixbit);
        }

        if (slack < 1) {
            base64[2] = '=';
        }

        if (slack < 2) {
            base64[3] = '=';
        }

        return base64;
    }

    protected static char getChar(int sixbit) {
        if (sixbit >= 0 && sixbit <= 25) {
            return (char) (65 + sixbit);
        }

        if (sixbit >= 26 && sixbit <= 51) {
            return (char) (97 + (sixbit - 26));
        }

        if (sixbit >= 52 && sixbit <= 61) {
            return (char) (48 + (sixbit - 52));
        }

        if (sixbit == 62) {
            return '+';
        }

        return sixbit != 63 ? '?' : '/';
    }
}

Related

  1. readObjectFromFile(File fileLocation)
  2. readObjectFromFile(String filename)
  3. saveObjectAsFile(String filename, Object object)
  4. writeObjectToFile(File fileLocation, Object obj)
  5. writeObjectToFile(Serializable obj, String filename)
  6. stringToObject(String s)
  7. getBytes(Serializable obj)
  8. deserialize(final File file, final long serialTtl)
  9. serialize(final File file, final Object o)