/** * 倒敘讀取文集最後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; }