加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 19:13:01 所属栏目:Java 来源:网络整理
导读:我想使用java来读取weblogic日志文件,而weblogic正在将日志写入其中(缓冲),但我只想读取内容,当我开始阅读它时. 我怎样才能做到这一点 ? public class DemoReader implements Runnable{ public void run() { File f = new File ("c:test.txt"); long leng

我想使用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建议的那样将其复制.之后,副本属于您,因此您可以随心所欲地做任何事情.

下面是一些应该实现您所需要的代码 – 它只是将文件逐字节复制到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).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读