今天新建了个文本文件,内容为:你好!测试文档!然后通过如下代码读取(myeclipse6.0环境),一开始没有转码都是正常显示的,后来安装了myeclipse7.0
,在7.0下无论我怎么转码都显示乱码,请问怎么解决:
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;public class Test {
public String readTxt(int off, int leng) {
RandomAccessFile r = null;
String str = "";
String str1 = "";
try {
r = new RandomAccessFile(new File("D:/aa.txt"), "r");
byte[] c = new byte[leng];
r.seek(off);
r.read(c);
str = new String(c);
str1 = new String(str.getBytes("iso8859-1"),"utf-8");
} catch (Exception e) {
try {
r.close();
} catch (IOException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}

return str1;
}
public static void main(String[] args) {
Test t = new Test();
String str = t.readTxt(0,5);
System.out.println(str);
}
}

解决方案 »

  1.   

    你的文件是什么编码的就用什么解码,Windows默认是gbk
      

  2.   

    楼主不用转码了,getBytes()那方法1.1后就过时了。我改了下,这次可以了输出前5个字符:你好!import java.io.File;
    import java.io.IOException;
    import java.io.RandomAccessFile;public class Test {
    public String readTxt(int off, int leng) {
    RandomAccessFile r = null;
    String str = "";
    //String str1 = "";
    try {
    r = new RandomAccessFile(new File("D:/aa.txt"), "r");
    byte[] c = new byte[leng];
    r.seek(off);
    r.read(c);
    str = new String(c);
    //str1 = new String(str.getBytes("GB2312"), "utf-8");
    } catch (Exception e) {
    try {
    r.close();
    } catch (IOException e1) {
    e1.printStackTrace();
    }
    e.printStackTrace();
    }
    return str;
    } public static void main(String[] args) {
    Test t = new Test();
    String str = t.readTxt(0, 5);
    System.out.println(str);
    }
    }