How can I end and resume writing a file using a single PrintWriter?

0

I'm working with a small project that performs the reading of the data of a spreadsheet, in order to facilitate the capture of the exceptions, I have a class called the Log Generator.

This class has a PrintWriter object that writes the Throwable that it captures and stores in a txt file, this object is instantiated when I start my view and closed when I close it, my intention is to know if it is possible to close write the file and resume it again using the same object at runtime?

My intention is to provide a button that allows the user of the application to see this file, but I'm a bit confused as to how to do this since the file is open for recording throughout the application.

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

    }
}
    
asked by anonymous 27.07.2017 / 17:00

1 answer

0

There is no problem in opening and closing your PrintWriter during the execution of the method, because if the file already exists and append is flagged as True (filewriter second parameter), 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 java Logger, as follows:

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 file looks like this:

Jun 06, 2017 10:07:26 PM SqlInsert insertBatch

WARNING: java.sql.BatchUpdateException: Batch entry 1 update move set example = GREEN SIGN, number = 1 was aborted: ERROR: syntax error at or near "GREEN" Position: 42 Call getNextException to see other errors in the batch .

    
27.07.2017 / 17:43