Java IO - 在写入其他应用程序时读取一个大文件

idi*_*ius 5 java file-io

我想使用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();
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

Gar*_*owe 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();
  }

}
Run Code Online (Sandbox Code Playgroud)

就这样吧。

日志文件注释

如果日志文件很大(例如 >1Gb),那么您确实应该考虑更改日志记录配置以合并滚动日志文件,该文件会自动将日志分解为更适合在 shell 编辑器中查看的块(例如 1Mb)维姆)。