public void open() { streamOpen = true; try { out = new BufferedWriter(new FileWriter(file, !config.willOverwrite())); } catch (IOException e) { e.printStackTrace(); } }
public LogFile(String filename, LoggerConfig config) { String path = FOLDER; this.config = config; // Date Check Date date = config.lastCreation(); Date now = new Date(System.currentTimeMillis()); int diff = (int) ((now.getTime() - date.getTime()) / (86400000)); // 86 400 000ms is the duration of a day in ms (1000*60*60*24) if (diff > config.getFolderDuration()) { // We need to create a new file path += formatter.format(now) + "/"; this.date = now.getTime() + ""; new File(path).mkdir(); } else path += formatter.format(date) + "/"; // Now we have our file file = new File(path + filename + ".log"); if (!file.exists()) { if (!new File(path).exists()) new File(path).mkdirs(); try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } open(); return; } // Overwrite check if (config.willOverwrite()) { file.delete(); try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } open(); } // Lines check int lines = 0; try { lines = countLines(file.getAbsolutePath()); } catch (IOException e) { e.printStackTrace(); } int maxLines = config.getMaxLines(); if (maxLines != 0 && lines > maxLines) { // We should delete lines : from the beginning to make lines fill 90% of Max Lines int startLine = (int) (lines - 0.9 * maxLines); try { ArrayList<String> buffer = new ArrayList<String>(); int line = 0; BufferedReader in = new BufferedReader(new FileReader(file)); // Our reader String s; while ((s = in.readLine()) != null) { line++; if (line > startLine) buffer.add(s); } in.close(); // Now we re-write out = new BufferedWriter(new FileWriter(file)); for (Iterator<String> i = buffer.iterator(); i.hasNext(); out.append(i.next() + "\r\n")) ; out.flush(); out.close(); out = null; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } open(); }