RandomAccessFile流的readLine()方法在读取含有非ASCⅡ字符的文件时,比如含有汉字的文件,会出现“乱码”现象。因此,需要把readLine()读取的字符串用“iso-8859-1”编码重新编码存放到byte数组中,然后再用当前机器的默认编码将该数组转化为字符串,操作如下:
String str = in.readLine();
byte b[] = str.getBytes("iso-8859-1");
String content = new String(b);
如果机器的默认编码是“GB2312”,那么
String content = new String(b);
等同于
String content = new String(b,"GB2312");
例如:
import java.io.*; public class Main { public static void main(String args[]) { RandomAccessFile in = null; try { in = new RandomAccessFile("Main.java","rw"); long length = in.length(); //获取文件的长度 long position = 0; in.seek(position); //将读取位置定位到文件的起始 while(position<length) { String str = in.readLine(); byte b[] = str.getBytes("iso-8859-1"); str = new String(b); position = in.getFilePointer(); System.out.println(str); } } catch(IOException e) {} } }
本文固定URL:https://www.dotcpp.com/qa/63