Read and Write a Log File
This is a Java class that can be used to write a log file and also read its contents into the console.
This is a Java class that can be used to write a log file and also read its contents into the console.
public class Log {
//write to log file
public void writeLog(String transaction, String fileName) throws IOException{
//create new log file identified by input file name, set file writer "true" to append.
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName +"_log.txt", true));
//write each entered transaction to file, break line, and close each time.
writer.write(transaction);
writer.newLine();
writer.close();
}
public void readLog(String fileName) throws IOException{
//define source path to look for correct file with matching fileName
Path source = Paths.get(fileName +"_log.txt");
//define charset for reader
Charset charset = Charset.forName("US-ASCII");
// instantiate reader, pass in source path and charset
BufferedReader reader = Files.newBufferedReader(source,charset);
String line = null;
//ID message for console output
System.out.println("Viewing Log for: " + fileName);
// output contents of file until end
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
}