java从文件尾部读文件

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;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值