我用IO流编写了一个程序,可是出现了一点错误,但找不到原因,请帮忙检查错误
import java.io.*;
class TestByte
{
public static void main(String[] args)
{
int j = 0;
byte[] datas = null;
byte[] get = new byte[5];

if(args.length == 0)
{
System.out.println("java -cp class TestByte[param]");
System.exit(0);
}
datas = args[0].getBytes();//把字符变成字节,并存储在一个字节数组中。

System.out.println("data数组里原始的值:" + new String(datas));

ByteArrayInputStream bint = new ByteArrayInputStream(datas);//存储并缓冲字节数组

bint.read(get,0,3);   //从输入流读取到字节数组。

for(int i = 0;i <3; i ++)
{
while(get[i]<0) j++;
}

if (j % 2 == 0)
 System.out.println("get数组里的数据:" + new String(get));
else 
{
bint.read(get,0,4);
System.out.println(new String(get));
}

ByteArrayOutputStream bout = new ByteArrayOutputStream();
bout.write(datas,0,4);  //从数组写入字节输出流 bout
System.out.println("重写datas数组里的数据: " + bout);
}
}另外,有其它的方法可以实现这个要求吗?最好附上代码.

解决方案 »

  1.   

    String类本身有substring方法,直接就是你想要的结果。
      

  2.   


    public static void main(String args[]){
    String a="我ABC汉DEF";
    System.out.println(a.substring(0,1));
    System.out.println(a.substring(0,2));
    System.out.println(a.substring(0,3));
    System.out.println(a.substring(0,4));
    System.out.println(a.substring(0,5));
    System.out.println(a.substring(0,6));
    System.out.println(a.substring(0,7));
    }结果:

    我A
    我AB
    我ABC
    我ABC汉
    我ABC汉D
    我ABC汉DE
      

  3.   

    都是unicode字符本来就一个代表一个
      

  4.   


    public String strByteCopy(String str,int nEnd){
    int count=0; if(nEnd==0)
    return "";
    byte[] byteStr=str.getBytes();
    int k=byteStr.length;

    if(k<=nEnd)
    return str; for(int i=0;i<nEnd;i++){
    if(byteStr[i]<0)
    count++;
    }

    if(count%2==0)
    return new String(byteStr,0,nEnd);
    else
    return new String(byteStr,0,nEnd-1);
    }
      

  5.   

    public String strByteCopy(String str,int nEnd){
    if(str.length()<=nEnd)
    return str;
    else{
    str=new String(str.getBytes());
    char[] charArray=str.toCharArray();
    char[] charArrayDesc=new char[nEnd];
    System.arraycopy(charArray,0,charArrayDesc,0,nEnd);
    return new String(charArrayDesc);
    }
    }
      

  6.   

    public String strByteCopy(String str,int nEnd){
    if(nEnd==0)
    return ""; if(str.length()<=nEnd)
    return str;
    else{
    str=new String(str.getBytes());
    char[] charArray=str.toCharArray();
    char[] charArrayDesc=new char[nEnd];
    System.arraycopy(charArray,0,charArrayDesc,0,nEnd);
    return new String(charArrayDesc);
    }
    }
      

  7.   

    public class Tools {      public static String splitString(String str, int len) {             return splitString(str, len, "...");      }      /**       * 字符串按字节截取       * @param str 原字符       * @param len 截取长度       * @param elide 省略符       * @return String       */       public static String splitString(String str,int len,String elide) {              if (str == null) {                     return "";              }              byte[] strByte = str.getBytes();              int strLen = strByte.length;              int elideLen = (elide.trim().length() == 0) ? 0 : elide.getBytes().length;              if (len >= strLen || len < 1) {                     return str;              }              if (len - elideLen > 0) {                     len = len - elideLen;              }              int count = 0;              for (int i = 0; i < len; i++) {                     int value = (int) strByte[i];                     if (value < 0) {                            count++;                     }              }              if (count % 2 != 0) {                     len = (len == 1) ? len + 1 : len - 1;              }              return new String(strByte, 0, len) + elide.trim();       }        public static void main(String args[]){
               String s="I am a student.我是一个学生";
               System.out.println(Tools.splitString(s,24));
               System.out.println(Tools.splitString(s,23));
               System.out.println(Tools.splitString(s,25));
               System.out.println(Tools.splitString(s,26));
          }}
      

  8.   

    用不着把字符串打散成为byte数组,那样太麻烦了。public class Test {
        public static void main(String[] args) {
            String str = "我ABC汉DEF";
            String newStr = truncteString(str, 6);
            System.out.println(newStr);
        }    private static String truncteString(String str, int byteLen) {
            StringBuffer sb = new StringBuffer();
            char[] chars = str.toCharArray();
            int count = 0;
            int i = 0;
            while (true) {
                if (chars[i] > 0xff) {
                    count += 2;
                } else {
                    count++;
                }
                if (count > byteLen) {
                    break;
                }
                sb.append(chars[i]);
                i++;
            }
            return sb.toString();
        }
    }
      

  9.   

    11楼,你这样做完全等于还是把字符串分解成了字符吗。java的字符是unicode,不可能出现半个的情况啊。只有分解成字节才会出现汉字半个的情况
      

  10.   

    hehe ...来个全的。。package com.song;class SplitString {
      private String str;
      private int byteNum;  public SplitString() {
        // do nothing
      }  public SplitString(String str, int byteNum) {
        this.str = str;
        this.byteNum = byteNum;
      }  public void splitIt() {
        byte bt[] = str.getBytes();
        System.out.println("Length of this String ===>" + bt.length);
        if (byteNum > 1) {
          if (bt[byteNum] < 0) {
            String substrx = new String(bt, 0, --byteNum);
            System.out.println(substrx);
          } else {
            String substrex = new String(bt, 0, byteNum);
            System.out.println(substrex);
          }    } else {
          if (byteNum == 1) {
            if (bt[byteNum] < 0) {
              String substr1 = new String(bt, 0, ++byteNum);
              System.out.println(substr1);
            } else {
              String subStr2 = new String(bt, 0, byteNum);
              System.out.println(subStr2);
            }
          } else {
            System.out.println("输入错误!!!请输入大于零的整数:");
          }
        }
      }
    }public class TestSplitString {
      public static void main(String args[]) {
        String str = "我ABC汉DEF";
        int num = 6;
        SplitString sptstr = new SplitString(str, num);
        sptstr.splitIt();
      }
    }
      

  11.   

    在Java里按字节截?Java使用Unicode编码,任何字符都是2个字节啊,所以无论怎么截都是按2个字节截下来的.
      

  12.   

    和11楼的一样,换个做法:-) 
             public static void main(String[] args) {
            String str = "我ABC汉DEF";
            for(int i=1 ; i<=str.length();i++){
                String newStr = truncteString(str, i);
                System.out.println("str="+newStr);
            }
        }   private static String truncteString(String str, int byteLen) {
    if(byteLen >= str.length())
                return str;
            String temp = str.substring(0, byteLen-1);
            StringBuffer sb = new StringBuffer(temp);
            char chars = str.charAt(byteLen-1);
            if(chars > 0xff)
                sb.append(str.substring(byteLen-1, byteLen));
            else
                sb.append(chars);
            return sb.toString();
        } 
      

  13.   


    public static String cut(String str, int len) { 
    String resultStr = ""; 
    for (int i = 0; i < str.length(); i++) { 
    if (resultStr.getBytes().length 
    + str.substring(i, i + 1).getBytes().length > len) { 
    break; 
    } else if (resultStr.getBytes().length 
    + str.substring(i, i + 1).getBytes().length <= len) { 
    resultStr = resultStr + str.substring(i, i + 1); 


    return resultStr; 

      

  14.   

       private static String getStrAsBytes(String src,int qlen){
       byte[] strBytes = src.getBytes();
       int rlen = 0;
       boolean chineseFlag = false;
           int srcLen = strBytes.length;
           if (qlen > srcLen) {
              System.out.println("you want more than the source");  
    } else {
    for (int i = 0; i < qlen; i++) {
    if(strBytes[i]>0 && strBytes[i]<256){
    rlen++;
    }
    else{
    if(chineseFlag){
    rlen++;
    chineseFlag = false;
    }else{
    chineseFlag = true;
    }
    }
    }
    }
       return src.substring(0,rlen);
       }
      

  15.   


    private static String getStrAsBytes(String src,int qlen){
       byte[] strBytes = src.getBytes();
       int rlen = 0;
       boolean chineseFlag = false;
           int srcLen = strBytes.length;
           if (qlen > srcLen) {
              System.out.println("you want more than the source");  
    } else {
    for (int i = 0; i < qlen; i++) {
    if(strBytes[i]>0 && strBytes[i]<256){
    rlen++;
    }
    else{
    if(chineseFlag){
    rlen++;
    chineseFlag = false;
    }else{
    chineseFlag = true;
    }
    }
    }
    }
       return src.substring(0,rlen);
       }
      

  16.   

    return new String(src.getBytes(), 0, len-(src.getBytes()[len] < 0?1:0))
      

  17.   

    写了一个实现了楼主的功能,请大家指出不足
    package com.ulic.breeze.csdn;
    /**
     * 从一个字符窜中截取指定的字节长度,字节长度由用户输入
     * 如果是汉字,不能截取半个字符,如"我ABC",输入3,截取
     * 结果为:我A,"ABC我",输入4,截取结果为ABC而非ABC
     * +我的半个
     * @author pengzj
     *
     */
    import java.io.*;
    public class InterceptString {
    public InterceptString(){

    }
    /**
     * 获得字符串中每个字符所占字节长度,存储在一个INT数组里面
     * @param string
     * @return 字符字节长度数组
     * @throws UnsupportedEncodingException
     */
    public static int[] intercept(String string)throws UnsupportedEncodingException{
    byte [] bytes = string.getBytes("US-ASCII");
    int[]length = new int[bytes.length];
    for(int i = 0;i < bytes.length;i++)
    length[i] = bytes[i] == 63? 2 : 1;

    return length;
    }
    /**
     * 获取符合条件的字符串
     * @param length 字符串每个字符所占字节长度数组
     * @param str 原字符串
     * @param num  字节长度
     * @return 截取的字符串
     */
    public static String getString(int[]length,String str,int num){
    String string= "";
    int index = 0;//原字符串中可以被截取的字符的最大索引
    int calLength = 0;
    for(int i = 0;i < length.length;i++){
    calLength += length[i];
    if(calLength > num){
    index = --i;
    break;
    }
    else index = i;
    }
    string = str.substring(0, index + 1);//截取字符串
    return string;
    }
    public static void main(String args[])throws UnsupportedEncodingException{
    String string = "我ABD多多,刘KK1232";
    int byte1 = 1;
    int[] length = intercept(string);
    String interceptString = getString(length,string,byte1);
    System.out.println("原字符串为:"+string+" 要求的字节长度为:"+byte1);
    System.out.println("不大于所要求字节长度的子字符串为:"+interceptString);
    //for(int i = 0;i < length.length;i++){
    //System.out.print(length[i]+" ");
    //}
    }}
      

  18.   

    //input 字符
    //index 需要截取的长度
    public static String getString(String input,int index){
    int temp=0;
    StringBuffer sb= new StringBuffer("");
    for(int i=0;i<input.length();i++){
    //获取每个字符
    String slice = input.substring(i,i+1);
    byte[] strByte = slice.getBytes();
    if(strByte.length==1){//长度为1,则为英文字符
    sb.append(slice);
    if(++temp==index){
    return sb.toString();
    }
    }else{//长度为2,应为中文字符
    if(temp+2>index){//如果长度再加2,超过需要截取的长度
    return sb.toString();
    }if(temp+2==index){//如果长度再加2等于需要截取的长度,加上中文字符,返回
    return sb.append(slice).toString();
    }else{//未超过截取字符,附加上中文字符
    sb.append(slice);
    temp+=2;
    }
    }
    }
    return sb.toString();
    }
      

  19.   

    class SplitString 
    {
        public static void main(String[] args) {
            String str = "我ABC汉DEF绝dd对ererd科d技发d123d3达";
            truncteString(str, 6);
         
        }
    private static void truncteString(String str, int byteLen) {
            StringBuffer sb = new StringBuffer();
            char[] chars = str.toCharArray();//数组化
            int count = 0; //统计当前累计的字节数
            int i = 0;     //标记当前已加到StringBuffer中的字符
            boolean show=false;
            while (i<chars.length) 
            {
             if(show)  //符合条件,输出。判断是否已经输出完整个字符串,若输出完毕,则退出循环。
                     
                 {
                     System.out.print(sb+"  ");
                     if(i==chars.length-1)
                      break;
                     show=false; // 否则将show置为false(不输出)、count清零,删除sb中已经输出的字符,重新累计。
                     sb.delete(0,i);
                     count=0;    
                 }
                if (chars[i] > 0xff)//判断是汉字还是字符           
                      count += 2;   //汉字两个字节
                else 
                      count++;             
                
                if (count > byteLen) 
                {
                    
                    show=true; 
                    continue;
                }
                sb.append(chars[i]);
                if(i==chars.length-1) //已经将string全部加载到了sb中以便输出
                {
                 show=true;
                 continue;
                }             
                i++;
            }
          
        }
    }