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!!!");
}
}
NIO按行读取文件内容,并打印出来
最新推荐文章于 2023-08-07 17:37:00 发布
本文详细介绍了如何使用Java NIO技术高效地读取和解析日志文件,包括创建文件通道、使用缓冲区进行读取以及处理最后一行的特殊处理方式。
981

被折叠的 条评论
为什么被折叠?



