我想使用java来读取weblogic日志文件,而weblogic正在将日志写入其中(缓冲),但我只想读取内容,当我开始阅读它时.
我怎样才能做到这一点 ?
public class DemoReader implements Runnable{
public void run() {
File f = new File ("c:\\test.txt");
long length = f.length();
long readedBytes = 0;
System.out.println(length);
try {
BufferedReader fr = new BufferedReader(new FileReader(f));
String line = "";
while((line = fr.readLine()) != null && readedBytes < length){
readedBytes += line.getBytes().length;
if(readedBytes > length){
break;
}else{
System.out.println(line);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
最佳答案
只要日志文件仅被锁定以进行写访问,您应该能够像@ karim79建议的那样将其复制.之后,副本属于您,因此您可以随心所欲地做任何事情.
原文链接:https://www.f2er.com/java/437755.html下面是一些应该实现您所需要的代码 – 它只是将文件逐字节复制到System.out流:
public class Main {
public static void main(String[] args) throws IOException {
// Identify your log file
File file = new File("path/to/your/logs/example.log");
// Work out the length at the start (before Weblogic starts writing again)
long size = file.length();
// Read in the data using a buffer
InputStream is = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(is);
long byteCount=0;
int result;
do {
// Read a single byte
result = bis.read();
if (result != -1)
{
// Do something with your log
System.out.write(result);
} else {
// Reached EOF
break;
}
byteCount++;
} while (byteCount
你去吧
有关日志文件的说明
如果日志文件很大(例如> 1Gb),那么您应该考虑更改日志配置以合并滚动日志文件,该日志文件会自动将日志分解为块(例如1Mb),这些块更适合在shell编辑器中查看(像vim).