JBoss log reading

1

This code takes my JBoss log file and displays the first 1000 lines. I would like to know how I can display the last 1000 lines?

private String log;

public void pesquisar() {

    String diretorioCorrente = System.getProperty("jboss.server.log.dir");

    File file = new File(diretorioCorrente + File.separator + "server.log");
    try {
        FileReader reader = new FileReader(file);
        BufferedReader input = new BufferedReader(reader);
        String linha;
        int contador = 0;
        StringBuilder sb = new StringBuilder();
        while ((linha = input.readLine()) != null) {
            sb.append(linha + "\n");
            contador++;
            if (contador > 1001) {
                break;
            }
        }
        input.close();
        log = sb.toString();
    } catch (IOException ioe) {
        System.out.println(ioe);
    }
}
    
asked by anonymous 15.05.2014 / 18:13

1 answer

2

The bad news

You will have to read the whole file to retrieve the last lines.

The good news

Java collections API classes make it easy to retrieve the latest N lines.

Procedure

First, declare ArrayList before while and add each line in the list instead of StringBuffer .

Then, remove the if (contador > 1001) stop criterion, as already suggested by @adelmo00 .

That way, your method will return all rows, right?

Finally, remove the most "old" rows from the vector when the number of rows exceeds 1000. Example:

public void pesquisar() {

    String diretorioCorrente = System.getProperty("jboss.server.log.dir");

    File file = new File(diretorioCorrente + File.separator + "server.log");
    try {
        FileReader reader = new FileReader(file);
        BufferedReader input = new BufferedReader(reader);
        String linha;
        int contador = 0;
        //inicia com um array interno de 1000 posições
        List<String> list = new ArrayList<String>(1000); 
        //adiciona todos os elementos, mas quando chegar a 1000, remove os mais velhos
        while ((linha = input.readLine()) != null) {
            list.add(linha);
            contador++;
            if (contador > 1000) {
                linha.remove(0);
            }
        }
        //escreve no StringBuffer, mas talvez não seja necessário
        StringBuilder sb = new StringBuilder();
        for (String str : list) {
            sb.append(str + "\n");
        }
        input.close();
        log = sb.toString();
    } catch (IOException ioe) {
        System.out.println(ioe);
    }
}
    
15.05.2014 / 19:22