java 判断是否读到文本的最后一条数据,直接得到文本的最后一条数据

本文介绍了一种使用Java编程语言读取文件并获取其最后一行数据的方法。通过RandomAccessFile类,代码实现了从指定路径读取文件,并利用特定算法定位到文件的最后一行,然后以指定的字符集读取这一行的内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本代码借鉴他人案例,如有侵权,请联系作者删除!!!!

示例代码如下:

public static void main(String[] args) {
    	//判断是否读到文本的最后一条数据
    	String lineLast=CollectionTest.getLastLineData("G:/hdf5_write_txt/a0909.txt","utf-8");
    	System.out.println("最后一条数据是:"+lineLast);
	}
//判断是否读到文件的最后一行数据
	public static String getLastLineData(String path,String charset) {
		String lastLine=null;
		RandomAccessFile raf=null;
		try {
			raf=new RandomAccessFile(path, "r");
			long lastLinePos=getLastLinePos(raf);
			long length=raf.length();
//			System.out.println("下标为:"+lastLinePos);
			byte[] bytes=new byte[(int)((length-1)-lastLinePos)];
			
			raf.read(bytes);
			if(charset == null) {
				lastLine=new String(bytes);
			}else {
				lastLine=new String(bytes,charset);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return lastLine;
	}
	public static long getLastLinePos(RandomAccessFile raf) {
		long lastLinePos = 0;
		// 获取文件占用字节数
		try {
			long len = raf.length();
			if (len > 0L){
				// 向前走一个字节
				long pos = len - 1;
				while (pos > 0)
				{
					pos--;
					// 移动指针
					raf.seek(pos);
					// 判断这个字节是不是回车符
					if (raf.readByte() == '\n')
					{
						 lastLinePos = pos;// 记录下位置
						// break;// 前移到会第一个回车符后结束
						return pos;
					}

				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return lastLinePos;
	}
相关部分知识,更详细可参照该博客地址:
https://blog.youkuaiyun.com/qq_21808961/article/details/83547919
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值