I want to write to a file in Java (that I have created succesfully also in Java).
I need to append lines to it and following the online instructions my code should work.
I'm never triggering errors (never do I reach a catch block), but I'm not getting any text in the textfile.
all variables are set and correct.
this is my code atm:
private void handleException () {
String fullPath = logPath + File.separator + logName;
File logFile = new File(fullPath);
if (!logFile.exists()) {
createLogFile(logFile);
}
String log = createLog();
addLogToFile(fullPath, log);
/*
if (Bad error of errorlogs > 20 ofazo) {
alertAdministrator();
}
*/
}
private void createLogFile(File logFile) {
try {
logFile.getParentFile().mkdirs(); //can cause duplicated files in MacOS
logFile.createNewFile();
} catch (IOException ex) {
Logger.getLogger(ErrorHandeling.class.getName()).log(Level.SEVERE, null, ex);
alertAdministrator("Error while writing logs.\nErrormessage: " + ex.toString());
}
}
private String createLog() {
String log = lineCount + ": " + message + "\n occurred in: file=" + writableStackTrace[0].getFileName() + " class=" + writableStackTrace[0].getClassName() + " method=" + writableStackTrace[0].getMethodName() + " line=" + writableStackTrace[0].getLineNumber() + "\n caused by: " + cause.getMessage();
return log;
}
private void addLogToFile(String fullPath, String log) {
try {
FileWriter fw = new FileWriter(fullPath, true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw);
out.println(log);
}
catch (IOException ex) {
alertAdministrator("Error while writing logs.\nErrormessage: " + ex.toString());
}
}
AutoCloseableRESOURCES.PrintWriter out = new PrintWriter(bw, true);