How can I end and resume recording a file using a single Printwriter?

Asked

Viewed 36 times

0

I am working with a small project that performs the reading of data from a spreadsheet, aiming to facilitate the capture of exceptions, I have a class called Log Generator.

This class has a Printwriter object that performs the writing of Throwable that captures and stores in a txt file, this object is instantiated when I start my view and when I close it, my intention is to know if it is possible to terminate the recording of the file and resume it again using the same object at runtime?

My intention is to provide a button that allows those who use the application to see this file, but I’m a little confused on how to do this since the file is open for recording throughout the application run.

package br.com.layoutbuilder.domain;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

public class GeradorLog {

    private PrintWriter out;

    public GeradorLog() {
        try {

            out = new PrintWriter(new FileWriter("LogAplicativo.txt", true));

        } catch (IOException e) {

            e.printStackTrace();

        }
    }

    public void gravaErro(Throwable erro) {

        out.print("Erro ocorrido em: ");
        out.println(new Date());
        out.print("Mensagem de erro: ");
        out.println(erro);
        out.print("Stacktrace: ");
        erro.printStackTrace(out);

    }

    public void close() {

        if (out != null) {
            out.flush();
            out.close();
        }

    }
}

1 answer

0


There is no problem opening and closing your Printwriter while running the method because if the file already exists and the append is flagged as True (Second parameter of filewriter), it will use the file that already exists.

public gerarLog(Throwable erro) {
    try {
        PrintWriter out = new PrintWriter(new FileWriter("LogAplicativo.txt", true));
        out.println("\nErro ocorrido em: " + new Date());
        out.println("Mensagem de erro: " + erro);
        out.print("Stacktrace: ");
        erro.printStackTrace(out);

        out.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
}

There is also the option to use the Java Logger, thus:

public void showErrorMessage(String sourceClass, String sourceMethod, Exception msg){
        try {

            Logger log = Logger.getLogger("My Log");

            Date dt = new Date();
            DateFormat brasil = new SimpleDateFormat ("ddMMyyyy");
            String data = brasil.format(dt);

            // Captura do diretório da aplicação a depender do sistema operacional
            String path = System.getProperty("user.dir");

            // Cria um arquivo log no formato arquivoddmmyyyy
            FileHandler fh = new FileHandler(path+"/biblioteca"+data+".log", true);
            SimpleFormatter formatter = new SimpleFormatter(); 
            fh.setFormatter(formatter);

            // Escreve a mensagem de erro no arquivo
            log.addHandler(fh);
            log.logp(Level.WARNING, sourceClass, sourceMethod, msg.toString());
            fh.close();

        } catch (IOException | SecurityException ex) {
            System.out.println(ex.getMessage());
        } 
    }

The final archive looks like this:

Jun 06, 2017 10:07:26 pm Sqlinsert inserirBatch

WARNING: java.sql.Batchupdateexception: Batch entry 1 update movement set exemplar = GREEN LIGHT, numero = 1 was aborted: ERROR: syntax error at or near "GREEN" Position: 42 Call getNextException to see other errors in the batch.

  • Thank you for clarifying my doubt Gustavo, very grateful!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.