Java IO - read a large file while another application writes to it

I want to use java to read the weblogic log file, while weblogic writes a log to it (buffered), but I only need to read the content that is present when I start reading it.

How can i do this?

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

}
+5
source share
2 answers

As long as the log file is locked for write access only, you can copy it, as @ karim79 suggested. After that, the copy belongs to you so that you can do whatever you like with it.

Here is some code that should do what you need to do - it just copies the byte file into the 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();
  }

}

And there you go.

Notes on log files

(, > 1 ), , , (, 1 ), (, vim).

+1

, N ( , 0 N ).

+3

All Articles