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

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

/**
	 * 倒叙读取文集最后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)+"
"; } else { System.out.println(line);// 输出为null,可以注释掉 } nextend--; x++; } nextend--; rf.seek(nextend); if (nextend == 0) {// 当文件指针退至文件开始处,输出第一行 System.out.println(rf.readLine()); runMessage+=rf.readLine()+"
"; } } //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; }

转载于:https://my.oschina.net/u/1182828/blog/172840

你可能感兴趣的:(解决RandomAccessFile.readLine()读取中文乱码)