JAVA IO - RandomAccessFile Seek学习

JAVA IO - RandomAccessFile Seek学习

import java.io.RandomAccessFile;

public class RandomAccessFileReadTest {
	public static void main(String args[]) {
		try {
			RandomAccessFile file = new RandomAccessFile(
					"c:\\work\\hello\\helloworld.txt", "r");
			for (int i = 0; i < 1000000; i++) {
				file.writeBytes(i + " hello world!\r\n");
			}
			
			tail(file, 2);

			file.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void tail(RandomAccessFile rf, int n) {
		StringBuffer sb = new StringBuffer(4096);
		try {
			long length = -1;
			length = rf.length() - 1;
			for (long i = length; i >= 0; i--) {
				rf.seek(i);
                int c = rf.read();
                if(c == '\r'){
                	n--;
                	if(n < 0){
                		System.out.println(sb.reverse().toString());
                		break;
                	}
                }
                sb.append( ( char )c);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}



你可能感兴趣的:(seek)