Log files are a great option to keep a history of the operations performed by the users of your application. There are several reasons for physically storing this type of information: auditing, maintenance, compliance, etc...
Anyway, it's always good to know how to implement the generation of a log file. So in today's post I made a video demonstrating how to perform this implementation:
Full code implemented in the video:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class LogGenerator {
public static void main(String[] args) throws IOException {
//Our goal...
for (int i = 0; i < 50; i++) {
generateLog("I = " + i);
}
}
public static void generateLog(String message) throws IOException {
Path path = Paths.get("C:/Users/55479/Desktop/logs/");
if(!Files.exists(path)) {
Files.createDirectory(path);
}
File log = new File("C:/Users/55479/Desktop/logs/logs.txt");
if(!log.exists()) {
log.createNewFile();
}
FileWriter fw = new FileWriter(log, true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(message);
bw.newLine();
bw.close();
fw.close();
}
}
Don't forget to make the necessary adjustments to the path of the created file, to adapt it to the path on your machine.
With this material you are ready to implement your log files in your next applications. Don't forget to practice the content presented, this is the best way to fix new content learned.
Comments