Java String Encode encodeString(String value)

Here you can find the source of encodeString(String value)

Description

Base64 encodes the specified string.

License

Apache License

Parameter

Parameter Description
value string to be encoded.

Return

String

Declaration

public static String encodeString(String value) throws IOException 

Method Source Code


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

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class Main {
    private static final int BUFFER_SIZE = 1024;
    public static final String ENCODING = "UTF-8";
    private static final int CHUNK_SIZE = 76;
    private static final byte[] CHUNK_SEPARATOR = "\r\n".getBytes();
    private static char[] B64CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
            .toCharArray();// w w  w  .j  a  va  2  s .com

    /**
     * Base64 encodes the specified string.  The encoded string is returned.
     *
     * @param value    string to be encoded.
     * @return String
     */
    public static String encodeString(String value) throws IOException {
        ByteArrayInputStream in = new ByteArrayInputStream(value.getBytes(ENCODING));
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        encode(in, out);
        return out.toString();
    }

    /**
     * Base64 encodes the specified string.  The encoded string is returned.
     *
     * @param value    string to be encoded.
     * @return byte[]
     */
    public static byte[] encode(String value) throws IOException {
        ByteArrayInputStream in = new ByteArrayInputStream(value.getBytes(ENCODING));
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        encode(in, out);
        return out.toByteArray();
    }

    /**
     * Base64 encodes the specified input.  The encoded bytes is returned.
     *
     * @param bytes   bytes to be encoded.
     * @return bytes
     */
    public static byte[] encode(byte[] bytes) throws IOException {
        ByteArrayInputStream in = new ByteArrayInputStream(bytes);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        encode(in, out);
        return out.toByteArray();
    }

    /**
     * Base64 encodes the specified input.  The encoded bytes is returned.
     *
     * @param in   input stream to be encoded.
     * @return bytes
     */
    public static byte[] encode(InputStream in) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        encode(in, out);
        return out.toByteArray();
    }

    /**
     * This method runs through the input stream, encoding it to the output
     * stream.
     */
    public static void encode(InputStream in, OutputStream out) throws IOException {
        byte buffer[] = new byte[BUFFER_SIZE];

        int c = -1;
        int pos = 0;
        int bytesWritten = 0;
        int remainder = 0;

        // read up to the buffer size number of characters, and loop until all input has been read
        while ((c = in.read(buffer, remainder, BUFFER_SIZE - remainder)) > 0) {

            // num characters is leftover, plus number chars read
            c += remainder;

            // The first step is to convert three bytes to four numbers of six bits. Each character in the
            // ASCII standard consists of seven bits. Base64 only uses 6 bits (corresponding to 2^6 = 64
            // characters) to ensure encoded data is printable and humanly readable. None of the special
            // characters available in ASCII are used. The 64 characters (hence the name Base64) are 10
            // digits, 26 lowercase characters, 26 uppercase characters as well as '+' and '/'.

            while (pos + 3 <= c) {
                bytesWritten = writeEncodedBytes(out, bytesWritten, buffer, pos, c - pos);
                pos += 3;
            }

            // number of bytes left in buffer...
            remainder = c - pos;

            // copy the remaining bytes to beginning of buffer
            for (int i = 0; i < 3; i++) {
                buffer[i] = (i < remainder) ? buffer[pos + i] : ((byte) 0);
            }

            // reset offset
            pos = 0;
        }

        // Write any remaining bytes
        if (remainder > 0) {
            bytesWritten = writeEncodedBytes(out, bytesWritten, buffer, pos, remainder);
        }

        return;
    }

    /**
     * Write out the next four bytes.  Will write a chunk separator when the chunk size number
     * of characters has been written.
     *
     * @param out         output stream
     * @param bytesWritten  number of bytes written so far
     * @param bytes         data buffer
     * @param pos           output index
     * @param remainder      number of bytes left to write
     *
     * @return current bytes witten on line
     */
    private static final int writeEncodedBytes(OutputStream out, int bytesWritten, byte[] bytes, int pos,
            int remainder) throws IOException {
        int index = -1;

        // always write out 4 bytes
        for (int i = 1; i <= 4; i++) {
            switch (i) {
            case 1: {
                index = (bytes[pos] & 0xfc) >> 2;
                break;
            }
            case 2: {
                index = ((bytes[pos] & 0x3) << 4) | ((bytes[pos + 1] & 0xf0) >>> 4);
                break;
            }
            case 3: {
                if (remainder <= 1) {
                    index = 64;
                } else {
                    index = ((bytes[pos + 1] & 0x0f) << 2) | ((bytes[pos + 2] & 0xc0) >>> 6);
                }
                break;
            }
            case 4: {
                if (remainder <= 2) {
                    index = 64;
                } else {
                    index = bytes[pos + 2] & 0x3f;
                }
                break;
            }
            }

            out.write(B64CHARS[index]);

            if (++bytesWritten == CHUNK_SIZE) {
                out.write(CHUNK_SEPARATOR);
                bytesWritten = 0;
            }
        }
        return bytesWritten;
    }
}

Related

  1. encodeString(String s, String charset)
  2. encodeString(String sourceString, String sysCharset, String charset)
  3. encodeString(String str)
  4. encodeString(String strData)
  5. encodeString(String text, String charsetName)
  6. encodeStringByUTF8(String str)
  7. encodeText(String str)
  8. encodeText(String str, String fromEnc, String toEnc)
  9. encodeTexts(String s)