---
title: "java获取文件最后一行和第一行记录"
author: "xiaoxiongsoft"
date: "2014-03-02T11:24:38Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2014-03-02T11:24:38Z"
id: 2024565
url: "https://xiaoxiongsoft.iteye.com/blog/2024565"
---

/ **
     *
     * @description 获取文件最后一行记录
     * @author xiaoxiong
     * @date 2012-10-12
     * @version 1.0.0
     * @param filePath  如："G:/module/billfilesynch/bak/CRBT021201207115068"
     * @return String
     * /
    public static String getFileLastLine(String filePath){
        RandomAccessFile raf;
        String lastLine = ""; 
        try {
            raf = new RandomAccessFile(filePath, "r");
            long len = raf.length(); 
            if (len != 0L) { 
              long pos = len - 1; 
              while (pos > 0) {  
                pos--; 
                raf.seek(pos); 
                if (raf.readByte() == '\n') { 
                  lastLine = raf.readLine(); 
                  break; 
                } 
              } 
            } 
            raf.close(); 
        } catch (Exception e) {
            e.printStackTrace();
        }
        return lastLine;
    }
    / **
     *
     * @description 获取文件第一行记录
     * @author xiaoxiong
     * @date 2012-10-12
     * @version 1.0.0
     * @param filePath
     * @return String
     * /
    public static String getFileFirstLine(String filePath){
        RandomAccessFile raf;
        String firstLine = ""; 
        try {
            raf = new RandomAccessFile(filePath, "r");
            firstLine=raf.readLine();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return firstLine;
    } 