Hola a todos, hoy os voy a explicar como podemos hacer una clase Log en Java.
Tener un pequeño log en una de nuestras aplicaciones es bastante útil, ya que nos puede dar información útil para arreglar problemas que pueden surgir en nuestra aplicación ya compilada.
Vamos a crear una clase llamada Log, le pondremos como atributos un BufferedReader y un String con la ruta del fichero:
import java.io.BufferedWriter; public class Log { private BufferedWriter buffered; private String ruta; }
Ese Buffered, deberemos poder abrirlo cuando lo necesitemos, por lo que crearemos un pequeño método:
private void open(boolean append) throws IOException { this.buffered = new BufferedWriter(new FileWriter(this.ruta, append)); }
El parámetro append es por si queremos reiniciar o añadir el contenido del fichero.
Ahora vamos a ver el tema de los constructores:
import java.io.BufferedWriter; import java.io.IOException; public class Log { private BufferedWriter buffered; private String ruta; public Log(String ruta) throws IOException { this.ruta = ruta; this.open(true); } public Log(String ruta, boolean reset) throws IOException { this.ruta = ruta; this.open(!reset); } private void open(boolean append) throws IOException { this.buffered = new BufferedWriter(new FileWriter(this.ruta, append)); } }
En uno, pasamos la ruta del fichero y en otro la ruta y si queremos o no resetearlo. Fíjate que llamo en el método open, el invierto el valor, ya que para resetearlo, nosotros le mandaremos un true y para que el buffered lo resetee realmente necesita un false, por eso lo invertimos.
Si abrimos el buffered, también deberiamos poder cerrarlo:
private void close() throws IOException{ this.buffered.close(); }
Ahora, lo más importante, necesitamos añadir lineas a nuestro log, lo haremos con el siguiente método:
public void addLine(String line) throws IOException { SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/YYYY HH:mm:ss"); String formatoFecha = sdf.format(new Date()); this.open(true); this.buffered.write("[" + formatoFecha + "] " + line + "\n"); this.close(); }
Lo importante, es que abrimos y cerramos el fichero.
Pero, ¿y si necesito coger el contenido para mostrarlo en mi aplicación?
Lo podemos hacer con este método:
public String[] getLines() throws FileNotFoundException, IOException { ArrayList<String> linesFile = new ArrayList<>(); BufferedReader br = new BufferedReader(new FileReader(this.ruta)); String line; while ((line = br.readLine()) != null) { linesFile.add(line); } br.close(); String[] lines = new String[linesFile.size()]; for (int i = 0; i < linesFile.size(); i++) { lines[i] = linesFile.get(i); } return lines; }
Como no sabemos cuantas lineas hay de primeras, lo metemos en un ArrayList, lo leo e inserto en el ArrayList, por último, lo metemos en un array.
Otra funcionalidad que vamos a meter es la de resetear el log:
public void resetLog() throws IOException{ this.open(false); this.close(); }
Os dejo la clase Log completa:
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; public class Log { private BufferedWriter buffered; private String ruta; public Log(String ruta) throws IOException { this.ruta = ruta; this.open(true); } public Log(String ruta, boolean reset) throws IOException { this.ruta = ruta; this.open(!reset); } private void open(boolean append) throws IOException { this.buffered = new BufferedWriter(new FileWriter(this.ruta, append)); } public void addLine(String line) throws IOException { SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/YYYY HH:mm:ss"); String formatoFecha = sdf.format(new Date()); this.open(true); this.buffered.write("[" + formatoFecha + "] " + line + "\n"); this.close(); } public String[] getLines() throws FileNotFoundException, IOException { ArrayList&amp;lt;String&amp;gt; linesFile = new ArrayList&amp;lt;&amp;gt;(); BufferedReader br = new BufferedReader(new FileReader(this.ruta)); String line; while ((line = br.readLine()) != null) { linesFile.add(line); } br.close(); String[] lines = new String[linesFile.size()]; for (int i = 0; i &amp;lt; linesFile.size(); i++) { lines[i] = linesFile.get(i); } return lines; } public void resetLog() throws IOException{ this.open(false); this.close(); } private void close() throws IOException{ this.buffered.close(); } }
Os dejo un pequeño ejemplo:
import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; public class Ejercicio_POO_DDR_24 { public static void main(String[] args) { try { Log myLog = new Log("./log.txt"); myLog.addLine("Linea 1"); myLog.addLine("Linea 2"); myLog.addLine("Linea 3"); myLog.addLine("Linea 4"); myLog.addLine("Linea 5"); String[] lines = myLog.getLines(); for (int i = 0; i < lines.length; i++) { System.out.println(lines[i]); } myLog.resetLog(); } catch (IOException ex) { Logger.getLogger(Ejercicio_POO_DDR_24.class.getName()).log(Level.SEVERE, null, ex); } } }
Te dejo un vídeo que te puede ser de ayuda:
Espero que os sea de ayuda. Si tenéis dudas, preguntad. Estamos para ayudarte.
Deja una respuesta