您的位置:首页 > 编程语言 > Java开发

Java按行读取正在被动态写入的大文件实例--使用RandomAccessFile(1)

2016-03-21 16:05 711 查看
[like Sunday like rain]

1.适用场景

适用于正在被动态按行写入大文件的读取和处理。

2.RandomAccessFile类主要方法

(1)length:获取当前文件的长度
(2)seek:指针从文件某个部分开始
(3)getFilePointer:指针当前所处位置

3.code

import java.io.File;
import java.io.RandomAccessFile;

/**
* Created by maixiaohai on 16/2/1.
*/
public class accessFileTest {
private static int SLEEP_TIME = 5000; // 5 seconds

public static void main(String[] args) throws Exception {
String filepath;
if (args.length == 1) {
filepath = args[0];
} else {
filepath = "/file/path";
}

long startIndex = 0;
boolean segmentFlag = true;
while (true) {
RandomAccessFile randomAccessFile = null;
try {
File file = new File(filepath);
try {
randomAccessFile = new RandomAccessFile(file, "r");
} catch (Exception e) {
e.printStackTrace();
//文件还未创建,等待
Thread.sleep(1 * 1000);
continue;
}

//获取当前文件的长度
long fileLength = randomAccessFile.length();

if (startIndex == 0) {
System.out.println("start");
startIndex = fileLength;
} else if (startIndex > fileLength){
//日志切换,此时需要把旧的的文件继续读完
if (segmentFlag) {
String path = "/old/file/path";
File fileNew = new File(path);
randomAccessFile = new RandomAccessFile(fileNew, "r");
segmentFlag = false;
} else {
startIndex = 0;
segmentFlag = true;
}
}
randomAccessFile.seek(startIndex);

String line = null;
while ((line = randomAccessFile.readLine()) != null) {
try {
//handle line
} catch (Exception e) {
//print log
e.printStackTrace();
}
}
//获取下次循环的开始指针
startIndex = randomAccessFile.getFilePointer();

} catch (Exception e) {
e.printStackTrace();
} finally {
try {
randomAccessFile.close();
Thread.sleep(SLEEP_TIME);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}


4.需要注意的地方

(1)本例仅适用于按行写入的文件
(2)本例假设被写入的文件在足够大时,会被移到另一个新的文件路径下,而新的写入还在旧的文件路径发生。如写入路径一直为/data/writtenfile,当文件达到20G时,会自动保存到路径/data/file1。 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息