2010-11-26 2 views
5

weblogicがログを書き込み中(バッファリング中)にJavaを使用してJavaを使用したいが、開始時に存在する読み込みコンテンツのみが必要それを読む。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

+0

いくつかのデモコード –

答えて

1

ログファイルが書き込みアクセス用にロックされている場合は、@ karim79が示唆しているとおりにコピーできるはずです。その後、コピーはあなたのものなので、好きなことを何でもできます。あなたが行く

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

} 

そして、そこ:それだけでコピーしたファイルのバイトバイトによってはSystem.outストリームに - ここで

はあなたが後にしているものを達成すべきいくつかのコードです。ログファイルの

ノート

ログファイルが膨大である場合(例えば> 1Gビット)は、あなたが本当に(自動的にチャンクにログを打破しますローリング・ログ・ファイルを組み込むために、あなたのログ設定を変更することを検討すべきですシェルエディタ(vimなど)での表示に適しています。

+0

を1行ずつ数えたほうがいいですし、1行ずつ処理することができます – idiotgenius

3

あなたが読むことを始めている現時点では、ファイルのサイズを取得し、その後つもりはないNにファイルが作家と0から、その内容によってロックされていないと仮定したバイトのN数を(読むことができます変更する)。

関連する問題