0

我正在使用以下代码读取日志文件并在数据库中存储匹配的模式。

public class MIScript {

//DB
public static void db(String email, String ip, String pdate, String hostname, String im) {


   // DATABASE INSERT


}

public void pop(File f, String IM) throws FileNotFoundException, IOException, InterruptedException {
    int pos = 0;
    RandomAccessFile file = new RandomAccessFile(f, "r");
    pos = (int) file.length() - (int) Math.min(file.length() - 1, file.length());

    file.seek(pos);
    for (; true; Thread.currentThread().sleep(1000)) {
        int l = (int) (file.length() - pos);
        if (l <= 0) {
            continue;
        }
        byte[] buf = new byte[l];
        int read = file.read(buf, 0, l);
        String out = new String(buf, 0, l);
        //   System.out.println(out);
        InputStream is = new ByteArrayInputStream(out.getBytes());
        BufferedReader in = new BufferedReader(new InputStreamReader(is));
        String line = null;
        while (((line = in.readLine()) != null)) {
            if (line.contains("LOG")) {

               // SOME CODE 

                //INSERT INTO DATABASE
                MIScript.db(// parameters //);

            }
        }
    }
}

public static void main(String[] args) {

    try {
        File pop = new File("d://ABC.log");
        MIScript tail1 = new MIScript();
        tail1.pop(pop, "TEST");


    } catch (ArrayIndexOutOfBoundsException ar) {
        System.out.println("Errrrr------" + ar);
        System.exit(1);
    } catch (Exception io) {
        io.printStackTrace();
        System.out.println("Errrrr2------" + io);
        System.exit(1);
    }
}

}

它在单个文件上效果很好,但我需要 4 个文件才能同步读取,请给我这样做的方法。我尝试使用 2 个文件来执行此操作,但这不起作用

4

1 回答 1

0

您需要在单独的线程中读取每个文件,并确保写入数据库的代码是线程安全的。

编辑:我把它放在评论中,但实际上它是答案的一部分:从 Java 7 你可以让文件系统在文件更改时给你回电话http://docs.oracle.com/javase/7/docs/api /java/nio/file/WatchService.html 这样你就不需要像你正在做的那样轮询文件大小......但你仍然需要每个文件1个线程。

WatchService 教程在这里:http ://docs.oracle.com/javase/tutorial/essential/io/notification.html

于 2013-06-14T08:47:35.923 回答