2010-11-26 56 views
5

我想在weblogic写入日志时使用java读取weblogic日志文件(缓冲),但我只想读取当我启动时存在的内容阅读它。Java IO - 在其他应用程序写入时读取大文件

我该怎么做?

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(); 
     } 
    } 

} 
+4

复制文件并从中读取。完成。 :) – karim79 2010-11-26 11:17:41

+0

增加了一些演示代码 – 2010-11-26 16:31:47

回答

1

只要日志文件仅锁定写入权限,您应该可以将其复制为@ karim79的建议。之后,副本属于你,所以你可以做任何你喜欢的事情。

下面是一些代码,应该实现你以后在做什么 - 它只是通过复制字节的文件字节到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<size); 

    // Printing this causes a final flush of the System.out buffer 
    System.out.printf("%nBytes read=%d",byteCount); 

    bis.close(); 
    is.close(); 
    } 

} 

而且你去那里。

上的日志文件注意

如果日志文件是巨大的(比如> 1GB),那么你真的应该考虑改变你的日志记录配置纳入一个滚动的日志文件,该文件将自动中断原木分解成块(比如1Mb),它们更适合在shell编辑器(比如vim)中查看。

3

你可以在你开始阅读那一刻文件的大小,然后读取N字节数(假定该文件不是由作家及其从0N内容锁定的是不会被改变)。

相关问题