`

java String to byte[]

    博客分类:
  • java
阅读更多

package mobile;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Vector;

/**
 *
 * @author zwg
 */
public class CBase64 {

    private static final char[] legalChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
            .toCharArray();

    private static Vector nodes = new Vector();

    /**
     * Split string into multiple strings
     * 
     * @param original
     *            Original string
     * @param separator
     *            Separator string in original string
     * @return Splitted string array
     */
    public static String[] split(String original, String separator) {
        nodes.removeAllElements();
        // Parse nodes into vector
        int index = original.indexOf(separator);
        while (index >= 0) {
            nodes.addElement(original.substring(0, index));
            original = original.substring(index + separator.length());
            index = original.indexOf(separator);
        }
        // Get the last node
        nodes.addElement(original);

        // Create splitted string array
        String[] result = new String[nodes.size()];
        if (nodes.size() > 0) {
            for (int loop = 0; loop < nodes.size(); loop++)
                result[loop] = (String) nodes.elementAt(loop);
        }
        return result;
    }

    /*
     * Replace all instances of a String in a String. @param s String to alter.
     * @param f String to look for. @param r String to replace it with, or null
     * to just remove it.
     */
    public static String replace(String s, String f, String r) {
        if (s == null)
            return s;
        if (f == null)
            return s;
        if (r == null)
            r = "";

        int index01 = s.indexOf(f);
        while (index01 != -1) {
            s = s.substring(0, index01) + r + s.substring(index01 + f.length());
            index01 += r.length();
            index01 = s.indexOf(f, index01);
        }
        return s;
    }

    /**
     * Method removes HTML tags from given string.
     * 
     * @param text
     *            Input parameter containing HTML tags (eg. <b>cat</b>)
     * @return String without HTML tags (eg. cat)
     */
    public static String removeHtml(String text) {
        try {
            int idx = text.indexOf("<");
            if (idx == -1)
                return text;

            String plainText = "";
            String htmlText = text;
            int htmlStartIndex = htmlText.indexOf("<", 0);
            if (htmlStartIndex == -1) {
                return text;
            }
            while (htmlStartIndex >= 0) {
                plainText += htmlText.substring(0, htmlStartIndex);
                int htmlEndIndex = htmlText.indexOf(">", htmlStartIndex);
                htmlText = htmlText.substring(htmlEndIndex + 1);
                htmlStartIndex = htmlText.indexOf("<", 0);
            }
            plainText = plainText.trim();
            return plainText;
        } catch (Exception e) {
            System.err.println("Error while removing HTML: " + e.toString());
            return text;
        }
    }

    /** Base64 encode the given data */
    public static String encode(byte[] data) {
        int start = 0;
        int len = data.length;
        StringBuffer buf = new StringBuffer(data.length * 3 / 2);

        int end = len - 3;
        int i = start;
        int n = 0;

        while (i <= end) {
            int d = ((((int) data[i]) & 0x0ff) << 16)
                    | ((((int) data[i + 1]) & 0x0ff) << 8)
                    | (((int) data[i + 2]) & 0x0ff);

            buf.append(legalChars[(d >> 18) & 63]);
            buf.append(legalChars[(d >> 12) & 63]);
            buf.append(legalChars[(d >> 6) & 63]);
            buf.append(legalChars[d & 63]);

            i += 3;

            if (n++ >= 14) {
                n = 0;
                buf.append(" ");
            }
        }

        if (i == start + len - 2) {
            int d = ((((int) data[i]) & 0x0ff) << 16)
                    | ((((int) data[i + 1]) & 255) << 8);

            buf.append(legalChars[(d >> 18) & 63]);
            buf.append(legalChars[(d >> 12) & 63]);
            buf.append(legalChars[(d >> 6) & 63]);
            buf.append("=");
        } else if (i == start + len - 1) {
            int d = (((int) data[i]) & 0x0ff) << 16;

            buf.append(legalChars[(d >> 18) & 63]);
            buf.append(legalChars[(d >> 12) & 63]);
            buf.append("==");
        }

        return buf.toString();
    }

    private static int decode(char c) {
        if (c >= 'A' && c <= 'Z')
            return ((int) c) - 65;
        else if (c >= 'a' && c <= 'z')
            return ((int) c) - 97 + 26;
        else if (c >= '0' && c <= '9')
            return ((int) c) - 48 + 26 + 26;
        else
            switch (c) {
            case '+':
                return 62;
            case '/':
                return 63;
            case '=':
                return 0;
            default:
                throw new RuntimeException("unexpected code: " + c);
            }
    }

    /**
     * Decodes the given Base64 encoded String to a new byte array. The byte
     * array holding the decoded data is returned.
     */

    public static byte[] decode(String s) {

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            decode(s, bos);
        } catch (IOException e) {
            throw new RuntimeException();
        }
        byte[] decodedBytes = bos.toByteArray();
        try {
            bos.close();
            bos = null;
        } catch (IOException ex) {
            System.err.println("Error while decoding BASE64: " + ex.toString());
        }
        return decodedBytes;
    }

    private static void decode(String s, OutputStream os) throws IOException {
        int i = 0;

        int len = s.length();

        while (true) {
            while (i < len && s.charAt(i) <= ' ')
                i++;

            if (i == len)
                break;

            int tri = (decode(s.charAt(i)) << 18)
                    + (decode(s.charAt(i + 1)) << 12)
                    + (decode(s.charAt(i + 2)) << 6)
                    + (decode(s.charAt(i + 3)));

            os.write((tri >> 16) & 255);
            if (s.charAt(i + 2) == '=')
                break;
            os.write((tri >> 8) & 255);
            if (s.charAt(i + 3) == '=')
                break;
            os.write(tri & 255);

            i += 4;
        }
    }
}


分享到:
评论
1 楼 hugang357 2011-09-17  

相关推荐

    Java String与Byte类型转换

    Java String与Byte类型转换;用到网络编程.

    Java中byte[]、String、Hex字符串等转换的方法

    主要介绍了Java中byte[]、String、Hex字符串等转换的方法,代码很简单,需要的朋友可以参考下

    andriod byte 转int,string,数组,互转

    byte转化工具类,可以实现byte转int,数组,string,小端取高位,低位等

    Java文件处理工具类--FileUtil

    public static byte[] readFileBinary(String fileName) throws Exception { FileInputStream fin = new FileInputStream(fileName); return readFileBinary(fin); } /** * 从输入流读取数据为二进制...

    java SM2加密算法实现 (不会用在下面留言)

    网上整理的sm2算法,希望对你有帮助 main方法测试 public static void ... plainText = new String(SM2Utils.decrypt(Util.hexToByte(prik), Util.hexToByte(cipherText))); System.out.println(plainText); }

    基于Java通讯开发jms源代码 (jms通讯开发源码)

    setByteProperty(String name, byte value) throws JMSException; void setShortProperty(String name, short value) throws JMSException; void setIntProperty(String name, int value) throws ...

    C#加密JAVA解密

    return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length); } public static string Decode(string data) { byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64); byte[] byIV = ...

    Java问题宝典2012版

    5、switch语句能否作用在byte上,能否作用在long上,能否作用在String上? 9 6、short s1 = 1; s1 = s1 + 1;有什么错? short s1 = 1; s1 += 1;有什么错? 9 7、char型变量中能不能存贮一个中文汉字?为什么? 9 8、用最...

    java代码获取myeclipse注册码.txt

    String verTime = new StringBuilder("-").append(new java.text.SimpleDateFormat("yyMMdd").format(cal.getTime())).append("0").toString(); String type = "YE3MP-"; String need = new StringBuilder...

    MD5的算法和使用

    * Constructs the MD5 object and sets the string whose MD5 is to be computed. * * @param inStr the &lt;code&gt;String&lt;/code&gt; whose MD5 is to be computed */ public MD5(String inStr) { this.inStr = ...

    DES对称分组密码系统的Java实现

    public byte[] Encripting(String plaintext,int i) throws Exception { byte[] bpt=plaintext.getBytes(); Cipher cf = Cipher.getInstance(algo[i]); if(skey==null)this.keyGenerating(); cf.init(Cipher....

    Java 将一个文本的内容写入另一个

    fos =new FileOutputStream("C:/to.txt");//打开会被清空 /*String s="测试数据"; byte[] buffer = s.getBytes(); fos.write(buffer);*/ byte [] buffer=new byte[10]; while(true){ int ...

    java压缩文件源码--ZipUtils

    log("unzip to "+getFileName(file.getPath())); FileOutputStream fos = new FileOutputStream(getFileName(file.getPath())+File.separator+newDir(file, entry.getName())); dest = new ...

    Android代码-okio

    Okio is a library that complements java.io and java.nio to make it much easier to access, store, and process your data. It started as a component of OkHttp, the capable ...

    JAVA基础之java的移位运算

    尽管我们在这个例子使用了byte 类型的值,但同样的基本的原则也适用于所有Java 的整数类型。 因为Java 使用2的补码来存储负数,并且因为Java 中的所有整数都是有符号的,这样应用位运算符可以容易地达到意想不到的...

    Java测试题1答案

    &lt;br&gt;4.A byte can be of what size 1)-128 to 127 2)(-2 power 8)-1 to 2 power 8 3)-255 to 256 4)depends on the particular implementation of the java virtual machine &lt;br&gt;5.哪些是Java...

    File_实用案例_实现文件拷贝_FileCopy.java

    public static void copy(String from_name, String to_name) throws IOException { File from_file = new File(from_name); // Get File objects from Strings File to_file = new File(to_name); // First...

    RSA公钥密码系统的Java实现

    * To change this template, choose Tools | Templates * and open the template in the editor. */ package rsa; import java.math.BigInteger; import java.util.Scanner; import java.util.Random; /** * *...

    JAVA实现DES算法

    JAVA实现DES加密 public class DES1 { public static final String KEY_ALGORITHM = "DES";... private static Key toKey(byte[] key) throws Exception{ DESKeySpec dks = new DESKeySpec(key);

Global site tag (gtag.js) - Google Analytics