Java IO—在其他应用程序写入大文件时读取该文件
我想在weblogic将日志写入(缓冲)日志文件时使用java读取weblogic日志文件,但我只想读取开始读取时出现的内容 我该怎么做Java IO—在其他应用程序写入大文件时读取该文件,java,file-io,Java,File Io,我想在weblogic将日志写入(缓冲)日志文件时使用java读取weblogic日志文件,但我只想读取开始读取时出现的内容 我该怎么做 public class DemoReader implements Runnable{ public void run() { File f = new File ("c:\\test.txt"); long length = f.length(); long readedBytes = 0;
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();
}
}
}
公共类DemoReader实现可运行{
公开募捐{
文件f=新文件(“c:\\test.txt”);
长长度=f.长度();
long readedBytes=0;
系统输出打印长度;
试一试{
BufferedReader fr=新的BufferedReader(新文件读取器(f));
字符串行=”;
while((line=fr.readLine())!=null&&readedBytes长度){
打破
}否则{
系统输出打印项次(行);
}
}
}catch(filenotfounde异常){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
}
}
只要日志文件仅为写访问而锁定,您就应该能够按照@karim79的建议复制它。之后,副本属于你,你可以用它做任何你喜欢的事情
下面是一些应该实现您所追求的目标的代码—它只是将文件逐字节复制到System.out stream:
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<size);
// Printing this causes a final flush of the System.out buffer
System.out.printf("%nBytes read=%d",byteCount);
bis.close();
is.close();
}
}
公共类主{
公共静态void main(字符串[]args)引发IOException{
//识别您的日志文件
File File=新文件(“path/to/your/logs/example.log”);
//在开始时计算长度(在Weblogic再次开始编写之前)
long size=file.length();
//使用缓冲区读入数据
InputStream is=新文件InputStream(文件);
BufferedInputStream bis=新的BufferedInputStream(is);
长字节数=0;
int结果;
做{
//读取单个字节
结果=bis.read();
如果(结果!=-1)
{
//用你的日志做点什么
系统输出写入(结果);
}否则{
//到达EOF
打破
}
字节计数++;
当您(BytCeNtT1GB)时,您应该考虑更改日志记录配置,以包含滚动日志文件,该日志文件将自动将日志分解为块(例如1MB),这更适合在shell编辑器(如VIM)中查看。.您可以在开始读取时获取文件的大小,然后读取N
字节数(假设文件未被写入程序锁定,并且其内容从0
到N
不会更改).复制文件并从中读取。完成。:)逐行计算字节更好,然后我们可以逐行处理它