首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

RandomAccessFile.readChar方法读取中文乱码的有关问题

2012-03-23 
RandomAccessFile.readChar方法读取中文乱码的问题读取的是个utf-16的文本文件,可是读取的却是乱码!utf-8

RandomAccessFile.readChar方法读取中文乱码的问题
读取的是个utf-16的文本文件,可是读取的却是乱码!utf-8也一样

Java code
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)

不明白这是什么意思

[解决办法]
试一下 RandomAccessFile中的 readUTF()方法;
[解决办法]
探讨
试一下 RandomAccessFile中的 readUTF()方法;

[解决办法]
Java code
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();        }            }}
[解决办法]
可能你文件是 GBK 的
Java code
        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();        } 

热点排行