ITeye博客

java从文件尾部读文件

luogen33 · 2011-09-01 00:44 · 编程语言 · Markdown

package read.file.form.emd;

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

public class ReadFileFromEndUtils {

public static void main(String args) {
	System.out.println(getUsefulStr("d:/file.txt", 1024, "machine"));

	System.out.println(getVersion(getUsefulStr("d:/file.txt", 1024,
			"machine"), "machine"));
}

/**
 * 获得 需要解析的字符串
 * 
 * @param fileName
 *            要解析的文件
 * @param len
 *            从后面的len个字节,开始处理
 * @return string 需要解析的字符串
 */
public static String getUsefulStr(String fileName, long len,
		String prexString) {
	RandomAccessFile randAccFile = null;
	try {
		// 获得随机读文件的流
		randAccFile = new RandomAccessFile(fileName, "r");
		// 获得文件的总长度,按字节统计
		long length = randAccFile.length();
		// 根据要读的字节数设置,文件读写指针的位置.
		randAccFile.seek(length - len);
		// 一次读10个字节,如果文件内容不足10个字节,则读剩下的字节
		// 将一次读取的字节数赋给byteread
		String str = "";
		while (true) {
			str = randAccFile.readLine();
			if (null == str) {
				break;
			}
			if (str.contains(prexString)) {
				// System.out.println(str);
				return str;
			}
		}
	} catch (FileNotFoundException e) {
		// 做日志,要解析的文件不存在
		e.printStackTrace();
	} catch (IOException e) {
		// 做日志,io流异常
		e.printStackTrace();
	} finally {
		if (randAccFile != null) {
			try {
				randAccFile.close();
			} catch (IOException e) {
				// 做日志,关闭io失败
				e.printStackTrace();
			}
		}
	}
	return null;
}

/**
 * 获得 version
 * 
 * @param str
 *            要处理的字符串
 * @param prexString
 *            版本号码前面的字符 ,例如:version=20010(该方法要更具,你的具体需求调整)
 * @return
 */
public static String getVersion(String str, String prexString) {
	int index = str.indexOf(prexString);
	String version = str.substring(index + prexString.length(), index
			+ prexString.length() + 6);
	return version;
}

}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。