您的位置:首页 > 其它

解决RandomAccessFile.readLine()读取中文乱码

2013-10-30 00:00 441 查看
/**
* 倒叙读取文集最后30行
* @param filename
* @return
*/
public static String read(String filename) {
String runMessage="";
RandomAccessFile rf = null;
try {
rf = new RandomAccessFile(filename, "r");
long len = rf.length();
long start = rf.getFilePointer();
long nextend = start + len;
String line;
rf.seek(nextend);
int c = -1;
int x = 0;
while ((nextend > start) & (x < 30)) {
c = rf.read();
if (c == '\n' || c == '\r') {
line = rf.readLine();
if (line != null) {
//System.out.println(line);
runMessage+=new String(line)+"<br>";
} else {
System.out.println(line);// 输出为null,可以注释掉
}
nextend--;
x++;
}
nextend--;
rf.seek(nextend);
if (nextend == 0) {// 当文件指针退至文件开始处,输出第一行
System.out.println(rf.readLine());
runMessage+=rf.readLine()+"<br>";
}
}
//System.out.println(runMessage);
runMessage=new String(runMessage.getBytes("8859_1"),"gb2312");//解决中文乱码
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (rf != null)
rf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return runMessage;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: