---
title: "从文件末尾进行读取的简单示例"
author: "haitan"
date: "2010-03-04T14:24:04Z"
tags: [".net", "C", "C#", "C++"]
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2010-03-04T14:24:04Z"
id: 607778
url: "https://haitan.iteye.com/blog/607778"
---

现实中有时会遇到需要从文件末尾开始读取的例子，比如读取文件的最后一行之类的。

    此时需要采用 RandomAccessFile 进行读取。

    下面只是一个简单的倒序读取文件的示例，以供参考。此示例不考虑性能，只介绍RandomAccessFile 的使用方法。

```
import java.io.RandomAccessFile;
import java.io.FileNotFoundException;
import java.io.IOException;

public class FromEndFileRead {
	public static void main(String args[]) {
		RandomAccessFile rf = null;
		try {
			rf = new RandomAccessFile("C:/net.log", "r");
			long len = rf.length();
			long nextend = len - 1;
			String line;
			rf.seek(nextend); //移动到文件最后
			int c = -1;
			while (nextend > 0) {
				c = rf.read();
				if (c == '\n' || c == '\r') {
					line = rf.readLine();
					if (line == null) {//处理文件末尾是空行的情况
						nextend--;
						rf.seek(nextend);
						continue;
					}
					System.out.println(new String(line.getBytes("ISO-8859-1"), "GB2312")); //处理中文问题
					nextend--;
				}
				nextend--;
				rf.seek(nextend);
				if (nextend == 0) {// 文件指针已退至开始处，输出第一行
					System.out.println(new String(rf.readLine().getBytes("ISO-8859-1"), "GB2312")); //处理中文问题
				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				rf.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
```