byte[] --> 字符串。
如:"text" --> byte[] --> "text";
现在我如何将byte数组中的数据还原成原来的字符串。谢谢。有满意答案果断结贴。!!

解决方案 »

  1.   

    public static String changeStr(String s) {
    StringBuffer sb = new StringBuffer(1024);
    if(s == null)
    return "";
    byte[] b = s.getBytes();
    for (byte by : b) {
    if (by == 63)
    by = (byte) (by & 100000);//or (by >> 1)+1
    sb.append((char)by);
    }
    return sb.toString();
    }
      

  2.   

    上面这段代码是之前写的,含义是传入一个string,然后将里面所有的?都替换成空格再作为string返回,里面涉及到你的问题了吧
      

  3.   

    不好意思,没考虑中文
    这样 public static String changeStr(String s) throws UnsupportedEncodingException {
    if(s == null)
    return "";
    byte[] b = s.getBytes("utf-8");
    return new String(b,"utf-8");
    }[code=Java]
    public static void main(String[] args) {
    String s = "窝窝啊a12321";
    try {
    System.out.println(changeStr(s));
    } catch (UnsupportedEncodingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }[/code]
      

  4.   

     public static String changeStr(byte[] b) {
            StringBuffer sb = new StringBuffer(1024);
            if(b == null)
                return "";
            for (byte by : b) {
                if (by == 63)
                    by = (byte) (by & 100000);//or (by >> 1)+1
                sb.append((char)by);
            }
            return sb.toString();
        }
      

  5.   

    我现在只想把 bytep[]中的数据转成原来的字符串。貌似代码有点问题。
      

  6.   

    你需求不是这样吗?就一个字符串,放到byte数组中,然后在把这个byte数组还原成原先的string,我还不明白你为什么要这么做,能说下你具体要做什么吗?
      

  7.   

    我对字符串进行了加密处理,以byte的方式写入文件中了,然后我再从文件中读取数据读取出来的byte[]数据经过解密 然后还原成加密钱的字符串。不知道说明白没有
      

  8.   

    明白了,直接用base64做吧,这样肯定没问题了 public static String StrToBase64(String s)
    throws UnsupportedEncodingException {
    if (s == null)
    return null;
    return (new sun.misc.BASE64Encoder()).encode(s.getBytes("UTF-8"));
    } // 把64bit编码转化成普通字符串
    public static String Base64ToStr(String s) {
    if (s == null)
    return null;
    BASE64Decoder decoder = new BASE64Decoder();
    try {
    byte[] b = decoder.decodeBuffer(s); return new String(b, "UTF-8"); } catch (Exception e) {
    return null;
    }
    }
      

  9.   

    你用过io吗?你是觉得不能从文件里面直接读出字符串吗?不会用字符流吗?
    lz的方式改变下,加密过程相当于直接用base64 encode,写到文件中,然后字符流读出的时候再做decode
      

  10.   

    可是我加密后的东西都是byte[]数组呀,如果转成其他的,我从文件中读出来又是一个麻烦事。
      

  11.   

    decoder.decodeBuffer这个方法可以直接传inputstream
      

  12.   

    意思就是你在将文件中的数据保存到inputstream中后,不要在去一个个字节去读到byte数组中了,让base64去做这个工作最后直接输出string
      

  13.   

      直接用new String(by[],code); 不过要先知道这个字节数组是什么编码的吧
      

  14.   

    直接用new String(by[],code); 不过要先知道这个字节数组是什么编码的吧