NIO按行读取文件内容,并打印出来

本文详细介绍了如何使用Java NIO技术高效地读取和解析日志文件,包括创建文件通道、使用缓冲区进行读取以及处理最后一行的特殊处理方式。
package com.broada.wssh.groovy;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class TestNio {

	public static void main(String args[]) throws Exception {

		int bufSize = 1200;

		File file = new File("E:\\monitor.log");
		
		FileInputStream fis = new FileInputStream(file);
		
		FileChannel fcin = fis.getChannel();

		ByteBuffer rBuffer = ByteBuffer.allocate(bufSize);



		String enterStr = "\n";

		try {
			StringBuffer strBuf = new StringBuffer("");

			int lineNum = 0;

			while (fcin.read(rBuffer) != -1) {

				int rSize = rBuffer.position();
				
				rBuffer.clear();

				String tempString = new String(rBuffer.array(), 0, rSize);
				
				if(fis.available() ==0){//最后一行,加入"\n分割符"
					tempString+="\n";
				}

				int fromIndex = 0;

				int endIndex = 0;
				

				while ((endIndex = tempString.indexOf(enterStr, fromIndex)) != -1) {

					String line = tempString.substring(fromIndex, endIndex);

					line = new String(strBuf.toString() + line);
					
					System.out.println("lineNum ="+ ++lineNum);
					
					System.out.println(line);

					strBuf.delete(0, strBuf.length());

					fromIndex = endIndex + 1;

				}

				if (rSize > tempString.length()) {

					strBuf.append(tempString.substring(fromIndex, tempString.length()));

				} else {

					strBuf.append(tempString.substring(fromIndex, rSize));

				}

			}

		} catch (IOException e) {

			e.printStackTrace();

		}

	

		System.out.print("OK!!!");

	}



}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值