从txt从前往后与从后往前读取起始时间并获得持续时间

import java.io.*;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;

public class Main {
    public static void main(String[] args) {
        String resultPath = "……\\result.txt";

        File file = new File(resultPath);
        StringBuilder builder = new StringBuilder();
        String beginTime = null;
        String endTime = null;
        try (RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r")) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(resultPath)));
            String readLine = null;
            while ((readLine = reader.readLine()) != null) {
                if (readLine.contains("Start Time")) {
                    String[] tmp = readLine.split("-");
                    beginTime = tmp[tmp.length - 1].replace(" ", "");
                    System.out.println(beginTime);
                }
            }


            // 指针位置开始为0,所以最大长度为 length-1
            long fileLastPointer = randomAccessFile.length() - 1;
            // 从后向前读取文件
            for (long i = fileLastPointer; i != -1 ; i--) {
                randomAccessFile.seek(i);
                int readByte = randomAccessFile.readByte();
                if (0xA == readByte) {
                    //  LF='\n'=0x0A 换行
                    if (i == fileLastPointer) {
                        // 如果是最后的换行,过滤掉
                        continue;
                    }
                    break;
                }
                if (0xD == readByte) {
                    //  CR ='\r'=0x0D 回车
                    if (i == fileLastPointer - 1) {
                        // 如果是倒数的回车也过滤掉
                        continue;
                    }
                    break;
                }
                builder.append((char) readByte);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        endTime = builder.reverse().toString().split("\t")[0];
        System.out.println(endTime);

        if (beginTime == null) {
            return;
        }
        LocalTime begin= LocalTime.parse(beginTime);
        LocalTime end = LocalTime.parse(endTime);

        long hours =  ChronoUnit.HOURS.between(begin, end);
        long minutes = ChronoUnit.MINUTES.between(begin, end) % 60;
        long seconds = ChronoUnit.SECONDS.between(begin, end) % 60;
        System.out.println("时间差为:" + hours + " 小时 " + minutes + " 分钟 " + seconds + " 秒");

    }
}

  • 6
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值