Java按行读取正在被动态写入的大文件实例--使用RandomAccessFile(1)
2016-03-21 16:05
711 查看
[like Sunday like rain]
(2)seek:指针从文件某个部分开始
(3)getFilePointer:指针当前所处位置
(2)本例假设被写入的文件在足够大时,会被移到另一个新的文件路径下,而新的写入还在旧的文件路径发生。如写入路径一直为/data/writtenfile,当文件达到20G时,会自动保存到路径/data/file1。
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。
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- c++11 + SDL2 + ffmpeg +OpenAL + java = Android播放器
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序
- 二叉查找树