日期:2014-05-19  浏览次数:20597 次

请教java中String和Byte转换问题
Java code

/**
     * 将字符串按字节位数截取
     * @param strValue 输入字符串
     * @param a 截取起始位数
     * @param b 截取结束位数
     * @return value
     * @throws java.lang.Exception
     */
    public String subStringByte(String strValue,int a,int b) throws Exception{
        String value=null;
        byte[] bytes = new byte[2048];
        System.out.println(bytes.length);
        bytes = strValue.getBytes();
        System.out.println(bytes.length);
        byte[] str = new byte[b-a];//要截取的字节码
        int index = 0;
        for(int i=a;i<b;i++) {
            str[index++] = bytes[i] ;//获取b-a的字节码
        }
        value = new String(str);//转化为string
        return value;
    }


开始bytes长度是2048,strValue.getBytes()之后怎么变成1024了,我输入的strValue参数很长时,需要截取的参数,a或b超过1024就数组越界,求各位解释下

------解决方案--------------------
byte[] bytes = new byte[2048];
此时bytes引用的是一个对象
bytes = strValue.getBytes();
这次bytes引用的是strValue.getBytes()返回的另一个对象。这个数组的长度跟2048是没有关系的。
------解决方案--------------------
byte[] bytes = new byte[2048];
bytes = strValue.getBytes(); 返回是是一个新的字节数组,也就是说bytes指向的引用变了。不在指向new byte[2048];
至于strValue.getBytes();是多大的字节数组,要去翻源码了。你也可以直接打印出他的长度是多少,看看结果。


------解决方案--------------------
我试了没问题啊。
Java code

public static void main(String[] args) throws Exception {
        StringBuffer sb = new StringBuffer();
        for(int i = 0;i < 9999;i++) {
            sb.append("艹x");
        }
        System.out.println(subStringByte(sb.toString(),10,20));
    }
    public static String subStringByte(String strValue,int a,int b) throws Exception{
        String value=null;
        byte[] bytes = new byte[2048];
        System.out.println(bytes.length);
        bytes = strValue.getBytes();
        System.out.println(bytes.length);
        byte[] str = new byte[b-a];//要截取的字节码
        int index = 0;
        for(int i=a;i<b;i++) {
            str[index++] = bytes[i] ;//获取b-a的字节码
        }
        value = new String(str);//转化为string
        return value;
    }