import java.io.*; import java.util.*; // Added this for get Time Class /** * The logging component of the project * @author Akbar Sherwani * @version v0.2 */ public class Logger { private File file; private FileWriter fWriter; private BufferedWriter writer; private boolean logging; /** * * Constructor for objects of class Logger. Takes an object of type File * Logging is set to true. * */ public Logger(File file1) throws IOException, NullPointerException { File dir = new File("Testing Output"); dir.mkdir(); file = new File(dir, file1.getName()); logging = true; write("Testing Log Started " + getTime(), 0); } /** * * Receives a string, that it should right to the next line in the file. * Checks again that logging is true. * * @param The message to be written to file. * @param Time in match */ public void write(String toFile, int time) { if(logging) { try{ fWriter = new FileWriter(file, true); writer = new BufferedWriter(fWriter); // write to file //writer.write(getTime()); writer.write(""+ time); writer.write(": "); writer.write(toFile); writer.newLine(); writer.flush(); writer.close(); } catch(IOException e){ System.out.println("IOException in Logger.write() method:" + e); } } } /** * * Creates a string with the current time and date. * @return A string in the format HH:MM:SS DD.MM.YYYY * */ private String getTime(){ Calendar timeStamp = Calendar.getInstance(); int hour = timeStamp.get(Calendar.HOUR_OF_DAY); String hourString = Integer.toString(hour); int min = timeStamp.get(Calendar.MINUTE); String minString = Integer.toString(min); int sec = timeStamp.get(Calendar.SECOND); String secString = Integer.toString(sec); int day = timeStamp.get(Calendar.DAY_OF_MONTH); String dayString = Integer.toString(day); int month = timeStamp.get(Calendar.MONTH) + 1; //Java takes January as 0 and December as 11. So +1 is required. String monthString = Integer.toString(month); int year = timeStamp.get(Calendar.YEAR); String yearString = Integer.toString(year); // The if statement pads this out so the seconds, minutes, days and months are always 2 digits. if (secString.length() == 1) { secString = "0" + secString; } if (minString.length() == 1) { minString = "0" + minString; } if (dayString.length() == 1) { dayString = "0" + dayString; } if (monthString.length() == 1) { monthString = "0" + monthString; } String time = hourString +":"+ minString +":"+ secString + " " + dayString + "." + monthString + "." + yearString; return time; } }