1. 程式人生 > >java從檔案末尾開始向前讀文字

java從檔案末尾開始向前讀文字

	public static List<String> getLine(String fileName, String startTime, int lines)
			throws FileNotFoundException, IOException {
		List<String> list = new ArrayList<String>();
		boolean already = false;
		RandomAccessFile rf = null;
		rf = new RandomAccessFile(fileName, "r");
		long len = rf.length();
		long start = rf.getFilePointer();
		long nextend = start + len - 1;
		String line;
		rf.seek(nextend);
		int c = -1;
		while (nextend > start) {
			c = rf.read();
			if (c == '\n' || c == '\r') {
				line = rf.readLine();
				if(already && lines >0){
					list.add(line);
					lines--;
				}
				if(line.startsWith(startTime)){
					//向前讀lines行
					list.add(line);
					lines--;
					already = true;
				}
				nextend--;
			}
			nextend--;
			if(lines == 0)
				break;
			rf.seek(nextend);
			if (nextend == 0) {// 當檔案指標退至檔案開始處,輸出第一行
				line = rf.readLine();
				if(line.startsWith(startTime)&&lines == 1)
					list.add(line);
			}
		}
		rf.close();
		return list;
	}