Java Byte Array Encode encode(byte[] bytes)

Here you can find the source of encode(byte[] bytes)

Description

encode

License

Open Source License

Declaration

public static byte[] encode(byte[] bytes) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.*;

public class Main {
    /**//from  www.ja  va 2s .  c  om
     * Table of the sixty-four characters that are used as
     * the Base64Util alphabet: [A-Za-z0-9+/]
     *
     * @since ostermillerutils 1.00.00
     */
    protected static final byte[] base64Chars = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
            'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
            'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2',
            '3', '4', '5', '6', '7', '8', '9', '+', '/', };
    private static final int END_OF_INPUT = -1;

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

    public static String encode(String string, String enc) throws UnsupportedEncodingException {
        return new String(encode(string.getBytes(enc)), enc);
    }

    public static byte[] encode(byte[] bytes) {
        return encode(bytes, false);
    }

    public static byte[] encode(byte[] bytes, boolean lineBreaks) {
        ByteArrayInputStream in = new ByteArrayInputStream(bytes);
        int mod;
        int length = bytes.length;
        if ((mod = length % 3) != 0) {
            length += 3 - mod;
        }
        length = length * 4 / 3;
        ByteArrayOutputStream out = new ByteArrayOutputStream(length);
        try {
            encode(in, out, lineBreaks);
        } catch (IOException x) {
            // This can't happen.
            // The input and output streams were constructed
            // on memory structures that don't actually use IO.
            throw new RuntimeException(x);
        }
        return out.toByteArray();
    }

    /**
     * Encode this file in Base64Util.
     * Line breaks will be inserted every 76 characters.
     *
     * @param fIn File to be encoded (will be overwritten).
     *
     * @since ostermillerutils 1.00.00
     */
    public static void encode(File fIn) throws IOException {
        encode(fIn, fIn, true);
    }

    /**
     * Encode this file in Base64Util.
     *
     * @param fIn File to be encoded (will be overwritten).
     * @param lineBreaks  Whether to insert line breaks every 76 characters in the output.
     * @throws IOException if an input or output error occurs.
     *
     * @since ostermillerutils 1.00.00
     */
    public static void encode(File fIn, boolean lineBreaks) throws IOException {
        encode(fIn, fIn, lineBreaks);
    }

    /**
     * Encode this file in Base64Util.
     * Line breaks will be inserted every 76 characters.
     *
     * @param fIn File to be encoded.
     * @param fOut File to which the results should be written (may be the same as fIn).
     * @throws IOException if an input or output error occurs.
     *
     * @since ostermillerutils 1.00.00
     */
    public static void encode(File fIn, File fOut) throws IOException {
        encode(fIn, fOut, true);
    }

    /**
     * Encode this file in Base64Util.
     *
     * @param fIn File to be encoded.
     * @param fOut File to which the results should be written (may be the same as fIn).
     * @param lineBreaks  Whether to insert line breaks every 76 characters in the output.
     * @throws IOException if an input or output error occurs.
     *
     * @since ostermillerutils 1.00.00
     */
    public static void encode(File fIn, File fOut, boolean lineBreaks) throws IOException {
        File temp = null;
        InputStream in = null;
        OutputStream out = null;
        try {
            in = new BufferedInputStream(new FileInputStream(fIn));
            temp = File.createTempFile("Base64Util", null, null);
            out = new BufferedOutputStream(new FileOutputStream(temp));
            encode(in, out, lineBreaks);
            in.close();
            in = null;
            out.flush();
            out.close();
            out = null;
        } finally {
            if (in != null) {
                in.close();
                in = null;
            }
            if (out != null) {
                out.flush();
                out.close();
                out = null;
            }
        }
    }

    /**
     * Encode data from the InputStream to the OutputStream in Base64Util.
     * Line breaks are inserted every 76 characters in the output.
     *
     * @param in Stream from which to read data that needs to be encoded.
     * @param out Stream to which to write encoded data.
     * @throws IOException if there is a problem reading or writing.
     *
     * @since ostermillerutils 1.00.00
     */
    public static void encode(InputStream in, OutputStream out) throws IOException {
        encode(in, out, true);
    }

    /**
     * Encode data from the InputStream to the OutputStream in Base64Util.
     *
     * @param in Stream from which to read data that needs to be encoded.
     * @param out Stream to which to write encoded data.
     * @param lineBreaks Whether to insert line breaks every 76 characters in the output.
     * @throws IOException if there is a problem reading or writing.
     *
     * @since ostermillerutils 1.00.00
     */
    public static void encode(InputStream in, OutputStream out, boolean lineBreaks) throws IOException {
        // Base64Util encoding converts three bytes of input to
        // four bytes of output
        int[] inBuffer = new int[3];
        int lineCount = 0;

        boolean done = false;
        while (!done && (inBuffer[0] = in.read()) != END_OF_INPUT) {
            // Fill the buffer
            inBuffer[1] = in.read();
            inBuffer[2] = in.read();

            // Calculate the out Buffer
            // The first byte of our in buffer will always be valid
            // but we must check to make sure the other two bytes
            // are not END_OF_INPUT before using them.
            // The basic idea is that the three bytes get split into
            // four bytes along these lines:
            //      [AAAAAABB] [BBBBCCCC] [CCDDDDDD]
            // [xxAAAAAA] [xxBBBBBB] [xxCCCCCC] [xxDDDDDD]
            // bytes are considered to be zero when absent.
            // the four bytes are then mapped to common ASCII symbols

            // A's: first six bits of first byte
            out.write(base64Chars[inBuffer[0] >> 2]);
            if (inBuffer[1] != END_OF_INPUT) {
                // B's: last two bits of first byte, first four bits of second byte
                out.write(base64Chars[((inBuffer[0] << 4) & 0x30) | (inBuffer[1] >> 4)]);
                if (inBuffer[2] != END_OF_INPUT) {
                    // C's: last four bits of second byte, first two bits of third byte
                    out.write(base64Chars[((inBuffer[1] << 2) & 0x3c) | (inBuffer[2] >> 6)]);
                    // D's: last six bits of third byte
                    out.write(base64Chars[inBuffer[2] & 0x3F]);
                } else {
                    // C's: last four bits of second byte
                    out.write(base64Chars[((inBuffer[1] << 2) & 0x3c)]);
                    // an equals sign for a character that is not a Base64Util character
                    out.write('=');
                    done = true;
                }
            } else {
                // B's: last two bits of first byte
                out.write(base64Chars[((inBuffer[0] << 4) & 0x30)]);
                // an equal signs for characters that is not a Base64Util characters
                out.write('=');
                out.write('=');
                done = true;
            }
            lineCount += 4;
            if (lineBreaks && lineCount >= 76) {
                out.write('\n');
                lineCount = 0;
            }
        }
        if (lineBreaks && lineCount >= 1) {
            out.write('\n');
            lineCount = 0;
        }
        out.flush();
    }
}

Related

  1. encode(byte[] b)
  2. encode(byte[] buf)
  3. encode(byte[] buff)
  4. encode(byte[] buffer, int offset, int len, Writer out)
  5. encode(byte[] bytes, boolean withNewLines)
  6. encode(byte[] data)
  7. encode(byte[] data)
  8. encode(byte[] in, int len)