Hello,
I'm trying to write to a text file but it's not working and I don't see why. I may be doing this all wrong, I don't know. My code is below, it is still at a skeleton stage.
The Function InitPerformancesReport correctly creates the file and when I get to WriteToPerformancesReport, it writes "Written to file" to the console so it is not throwing an exception apparently. However, nothing is written to the file. I even tried to add an out.flush(); and out.write(); inside the function just for testing purposes but to no avail. I end up with a 0 byte file. What am I doing wrong ?
Thank you for your help!!
public class Monitoring { private static DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH_mm_ss"); private static LocalDateTime now; private static String perfLogFile; private static FileWriter writer; private static BufferedWriter out; public static void InitPerformancesReport(String suffix) { now = LocalDateTime.now(); perfLogFile = dtf.format(now) + "_" + suffix + ".log"; String directoryName = "D:\\TempsDeResponse"; File directory = new File(directoryName); File file = new File(directoryName + "\\" + perfLogFile); if (!directory.exists()) { directory.mkdir(); } try { if (file.createNewFile()) { System.out.println("File is created"); } } catch (IOException e) { // TODO Auto-generated catch block System.out.println("Cannot create file"); e.printStackTrace(); } try { writer = new FileWriter(perfLogFile); out = new BufferedWriter(writer); } catch (IOException e) { // TODO Auto-generated catch block System.out.println("Cannot create writer"); e.printStackTrace(); } } public static void WriteToPerformancesReport(String transactionName, Long transactionTime) { try { out.write("TEST"); out.newLine(); System.out.println("Written to file"); } catch (IOException e) { // TODO Auto-generated catch block System.out.println("Cannot write to file"); e.printStackTrace(); } } public static void ExportPerformancesReport() { try { out.close(); writer.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }