java中RandomAccessFile类的Demo
java使用RandomAccessFile可以完成文件的随机读取,以下自己写了一个小demo,希望对大家有帮助。
public static void main(String[] args) {
File file1 = new File("test_project/test1.log");
File file2 = new File("test_project/test2.log");
// 上锁
ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
readWriteLock.writeLock().lock();
try {
if(!file1.getParentFile().exists()){
System.out.println("文件不存在");
}
// 创建要写入的文件
if(!file2.getParentFile().exists()){
file2.getParentFile().mkdirs();
}
// 打开文件
RandomAccessFile stroDf1 = new RandomAccessFile(file1, "r");
RandomAccessFile stroDf2 = new RandomAccessFile(file2, "rw");
//逐行读取
String line = null;
long point = 0;
StringBuilder sb = new StringBuilder();
while ((line = stroDf1.readLine()) != null){
// 逐行读取,逐行写入
sb.append(line).append("\r\n");
stroDf2.writeBytes(sb.toString());
// 清空缓冲区
sb.setLength(0);
// 获取最近读取的坐标点,移动到坐标点,从坐标点继续读取
/* point = stroDf1.getFilePointer();
stroDf1.seek(point);
stroDf1.readLine();*/
}
}catch (IOException e){
e.printStackTrace();
}finally {
// 释放锁
readWriteLock.writeLock().unlock();
}
}
使用的时候大家可以结合自己具体的业务场景选择。