RandomAccessFile 的readChar() 的结束标志是什么
如果定义 
RandomAccessFile raf=new RandomAccessFile(file,"rw");
char c;
         c=raf.readChar();
其中file为txt文本 里面全是汉字,为什么char c;里面的读出来的是乱码,不是Java里面一个char是2个字节吗,可以是汉字啊

解决方案 »

  1.   

    java中char是2个字节这没问题,因为用的unicode编码,而一个汉字用unicode编码也是2个字节。
    出现这个问题可能是你的文件采用的是UTF-8编码方式,好像是3个字节一个中文,所以你的会出现乱码。
      

  2.   

    readChar() 不能像 read 等 InputStream 中的方法那样有一个结束标志。但是你可以通过 length() 和 getFilePointer() 来进行控制,否则你如果一直读的话,最终会得到一个异常。RandomAccessFile 中的方法除了读时用到的 read(),read(byte[] b),read(byte[] b, int off, int len) 
    和写是用到的:write(byte[] b) , write(byte[] b, int off, int len) ,write(int b)  看似正常外,其它的读写方法似乎都不正常。呵呵。我并不知道如何使用它们。但是有一点可以肯定,你用的 readChar(); 方法并不能依照你的意愿返回一个你想要的字符。你看 API 就可以知道。类似的这些 readXXX 方法,其实都是在和字节打交道,就说 readChar(); 吧,其实它返回的是“两个字节”而不是一个字符。就像 API 文档中说的:我把关注放在了红色文字上,至于 Reads a character from this file. 我认为是个歧义,或者说它这里的 character 与 UNICODE 有所关联,再或者是我没有真正的体会吧,呵呵。当然我把关注红色文字也是有证据的,看下面的代码():                //E:\\ttsd.txt 为 GBK 编码。且内容中,第一个字符为“中”
    RandomAccessFile randomAccessFile = new RandomAccessFile("E:\\ttsd.txt","r");
    char c = randomAccessFile.readChar();
    randomAccessFile.close();
    int i = (int)c;//54992
    System.out.println(i);
    //54992 的二进制为:1101011011010000
    System.out.println(Integer.toBinaryString(i));// 输出:1101011011010000
    //1101011011010000 为16位,两个字节,且分别是:11010110 和 11010000
    //11010110 对应的 byte 为 -42。  11010000 对应的 byte 为 -48 。即 1101011011010000 为:
    byte[] b = {-42,-48};
    String s = new String(b,"GBK"); // 得到了“中”
    System.out.println(s);
    // 由此可见,readChar 方法,就像 API 文档中所说的:This method reads two bytes from the file 。在该例中读到的两个字节分别为:-42  和 -48
      

  3.   

    System.out.println(new String(c));