RandomAccessFile raf=
new RandomAccessFile("r.txt","rw");
raf.writeInt(4);
raf.writeLong(6);
System.out.println(raf.getFilePointer());//12
raf.writeUTF("zhou");
System.out.println(raf.getFilePointer());//18
raf.close();writeUTF()写了4个字节的字符串,游标的位置应该停留在16啊,为什么为多了2个字节的长度呢?
请各位朋友帮忙解释一下。
java

解决方案 »

  1.   

    First, two bytes are written to the file, starting at the current file pointer, as if by the writeShort method giving the number of bytes to follow. This value is the number of bytes actually written out, not the length of the string. Following the length, each character of the string is output, in sequence, using the modified UTF-8 encoding for each character. 
    就是首先写入2个字节的长度
    然后才写入具体字符串
      

  2.   

    JDK1.6 APIwriteUTF
    public final void writeUTF(String str)
                        throws IOException使用 modified UTF-8 编码以与机器无关的方式将一个字符串写入该文件。 
    首先,把两个字节从文件的当前文件指针写入到此文件,类似于使用 writeShort 方法并给定要跟随的字节数。此值是实际写出的字节数,而不是该字符串的长度。在该长度之后,按顺序输出该字符串的每个字符,并对每个字符使用 UTF-8 修改版编码。 
    指定者:
    接口 DataOutput 中的 writeUTF
    参数:
    str - 要写入的字符串。 
    抛出: 
    IOException - 如果发生 I/O 错误。