读取的是个utf-16的文本文件,可是读取的却是乱码!utf-8也一样
public class StringReaderTest {
    public static void main(String[] args)
    {
        try
        {
            RandomAccessFile raf = new RandomAccessFile("/home/timing/test.txt","r");
            int a;
            int i=0;
            do
            {
                i++;
                a = raf.readChar();
                System.out.println(i + ":" + (char)a);
            }while(a != -1);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        
    }}
PS:java api文档上说:
如果按顺序读取的字节为 b1 和 b2,其中 0 <= b1, b2 <= 255,则结果将等于:    (char)((b1 << 8) | b2)
     

不明白这是什么意思

解决方案 »

  1.   

    试一下 RandomAccessFile中的 readUTF()方法;
      

  2.   


    public class StringReaderTest {
        public static void main(String[] args)
        {
            try
            {
                RandomAccessFile raf = new RandomAccessFile("/home/test/test.txt","r");
                int a;
                int i=0;
                String str;
                while(( str=raf.readLine())!=null){
                 String strTemp =new String(
             str.getBytes("ISO8859-1"),"UTF8");
                 System.out.println(strTemp);
                }
            } catch(Exception e)
            {
                e.printStackTrace();
            }
            
        }}
      

  3.   

    可能你文件是 GBK 的 try {
    RandomAccessFile raf = new RandomAccessFile("/home/timing/test.txt", "r");
    byte[] bytes = new byte[2];
    long length = raf.length();
    for (long i=0; i<length; i++) {
    bytes[0] = raf.readByte();
    if (bytes[0] < 0) {
    bytes[1] = raf.readByte(); i++;
    System.out.print(new String(bytes));
    } else {
    System.out.print((char)bytes[0]);
    }
    }
    } catch(Exception e) {
    e.printStackTrace();
    }
      

  4.   

    我现在按照字节读取,使用String newLine = new String(line.getBytes("ISO-8859-1"),"GBK");方式竟然转码成功,乱码复原为汉字。
      

  5.   

    String st=new String(raf.readLine().getBytes("ISO-8859-1"),"GBK");
    可以把中午乱码解决掉!