代码之家  ›  专栏  ›  技术社区  ›  idiotgenius

Java IO—在其他应用程序写入大文件时读取该文件

  •  5
  • idiotgenius  · 技术社区  · 14 年前

    我想在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; 
            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();
            }
        }
    
    }
    
    2 回复  |  直到 14 年前
        1
  •  1
  •   Gary    14 年前

    只要日志文件只为写访问而锁定,您就应该能够按照@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)中查看。

        2
  •  3
  •   khachik    14 年前

    您可以在开始读取时获取文件的大小,然后读取 N 字节数(假设文件未被写入程序锁定,其内容来自 0 N个 不会改变的)。