Java中如何创建指定大小字节数的字符串
如:想创建一个固定长度为12个字节的字符串如何创建呢.谢谢

解决方案 »

  1.   

    这个没法控制,自己判断字节数吧,或者字节写个字符串类
    如果想创建12个字节的,空白字符串,可以用new String(byte[])构造函数
    for example
    byte[] b = new byte[12];
    Arrays.fill(b, (byte)0x32);
    String s = new String(b);
      

  2.   


    lz的字符串是指字符串数组?简单的一个String?
      

  3.   

    java中提供有构造方法,String(byte[] bytes, Charset charset) ,用特定的字符集把字节数组解码成string字符串,在创建字节数组时只要保证为12个字节就行,但转换成的字符串不一定等于字节数组的长度
      

  4.   

    for example
    byte[] b = new byte[12];
    Arrays.fill(b, (byte)0); //二进制0
    String s = new String(b);
      

  5.   

    byte 不是一个字节的吗.我通过
    byte[] b = new byte[12];String s = new String(b); outs.writeChars(s);
    文件大小怎么是24个字节的呢
      

  6.   

    outs.writeChars(s); 改成 outs.writeBytes(s);
    按字节输出而不是按字符输出
      

  7.   

    javadoc里有说明writeCharspublic final void writeChars(String s)
                          throws IOException将字符串按字符顺序写入基础输出流。通过 writeChar 方法将每个字符写入数据输出流。如果没有抛出异常,则计数器 written 增加 s 长度的两倍。 指定者:
    接口 DataOutput 中的 writeChars
    参数:
    s - 要写入的 String 值。 
    抛出: 
    IOException - 如果发生 I/O 错误。
    另请参见:
    writeChar(int), FilterOutputStream.out
    writeBytespublic final void writeBytes(String s)
                          throws IOException将字符串按字节顺序写出到基础输出流中。按顺序写出字符串中每个字符,丢弃其八个高位。如果没有抛出异常,则计数器 written 增加 s 的长度。 指定者:
    接口 DataOutput 中的 writeBytes
    参数:
    s - 要写入的字节字符串。 
    抛出: 
    IOException - 如果发生 I/O 错误。
    另请参见:
    FilterOutputStream.out