Writing records to CSV file periodically using Java

Ranjeet :

I am trying to fetch server health information periodically (I am planning to use cron job for the same) and storing same in a CSV file. Issue is, below code stores only one line .i.e. only latest record is stored in CSV file and previous record is getting deleted. As per my requirement, CSV file should contain records for each execution of below java code.

Need help to resolve the issue. I am not supposed to use Maven or any external jar for this requirement.

public class MachineHealthCheckReportGeneration {

private final String environmentname = "DEV";
private final String applicationname = "XYZ";
private final String username = System.getProperty("user.name"); // DO NOT CHANGE ANYTHING IN THIS THIS LINE
private final String csvfiledir = "D:\\logs\\monitoring\\server\\" + environmentname;
private Map<String, String> systeminformation = null;


/// DO NOT EDIT AFTER THIS LINE ///
private Map<String, String> getMachineHealthCehckReport() {

    systeminformation = new HashMap<>();
    OperatingSystemMXBean osbean = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class);

    systeminformation.put("Application", applicationname);
    systeminformation.put("CaptureTime", Instant.now().toString());
    try {
        systeminformation.put("HostName", InetAddress.getLocalHost().getHostName());
    } catch (UnknownHostException e) {
        System.err.println("Failed to get Hostname...");
        e.printStackTrace();
    }
    try {
        systeminformation.put("IPAddress", InetAddress.getLocalHost().getHostAddress());
    } catch (UnknownHostException e) {
        System.err.println("Failed to get IP Address...");
        e.printStackTrace();
    }
    systeminformation.put("CPUCount", Long.toString(osbean.getAvailableProcessors()));
    systeminformation.put("SystemCPULoad", Double.toString(osbean.getSystemCpuLoad()));
    systeminformation.put("ProcessCPULoad", Double.toString(osbean.getProcessCpuLoad()).substring(0, 4));
    systeminformation.put("ProcessCPUTime", Long.toString(osbean.getProcessCpuTime() / (1000 * 1000)) + " ms");
    systeminformation.put("FreePhysicalMemory",
            Long.toString(osbean.getFreePhysicalMemorySize() / (1024 * 1024 * 1024)) + " GB");
    systeminformation.put("TotalPhysicalMemory",
            Long.toString(osbean.getTotalPhysicalMemorySize() / (1024 * 1024 * 1024)) + " GB");
    systeminformation.put("CommittedVirtualMemory",
            Long.toString(osbean.getCommittedVirtualMemorySize() / (1024 * 1024)) + " MB");
    systeminformation.put("FreeSwapSpace",
            Long.toString(osbean.getFreeSwapSpaceSize() / (1024 * 1024 * 1024)) + " GB");
    systeminformation.put("TotalSwapSpace",
            Long.toString(osbean.getTotalSwapSpaceSize() / (1024 * 1024 * 1024)) + " GB");
    systeminformation.put("D:\\logs",
            Long.toString(new File("D:\\logs").getFreeSpace() / (1024 * 1024 * 1024)) + " GB");
    systeminformation.put("D:\\config",
            Long.toString(new File("D:\\config").getFreeSpace() / (1024 * 1024 * 1024)) + " GB");

    System.out.println(systeminformation);
    return systeminformation;
}

protected boolean printMachineHealthCheckReport() {

    String csvfileline = null;
    boolean isreportprinted = false;

    // create csv file directory and file if it does not exists
    File directory = new File(String.valueOf(csvfiledir));
    File file = new File(String.valueOf(csvfiledir + "/" + systeminformation.get("HostName") + ".csv"));
    if (!directory.exists()) {
        directory.mkdirs();
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                System.err.println("Failed to create file : " + file);
                e.printStackTrace();
            }
        }
    }

    try {
        FileWriter writer = new FileWriter(file);

        // insert header if file is empty
        if (file.length() == 0) {
            writer.append(
                    "Application,CaptureTime,HostName,IPAddress,CPUCount,SystemCPULoad,ProcessCPULoad,ProcessCPUTime,FreePhysicalMemory,TotalPhysicalMemory,CommittedVirtualMemory,FreeSwapSapce,TotalSwapSpace");
        }
        csvfileline = "\r\n"+systeminformation.get("Application") + ",";
        csvfileline = csvfileline + systeminformation.get("CaptureTime") + ",";
        csvfileline = csvfileline + systeminformation.get("HostName") + ",";
        csvfileline = csvfileline + systeminformation.get("IPAddress") + ",";
        csvfileline = csvfileline + systeminformation.get("CPUCount") + ",";
        csvfileline = csvfileline + systeminformation.get("SystemCPULoad") + ",";
        csvfileline = csvfileline + systeminformation.get("ProcessCPULoad") + ",";
        csvfileline = csvfileline + systeminformation.get("ProcessCPUTime") + ",";
        csvfileline = csvfileline + systeminformation.get("FreePhysicalMemory") + ",";
        csvfileline = csvfileline + systeminformation.get("TotalPhysicalMemory") + ",";
        csvfileline = csvfileline + systeminformation.get("CommittedVirtualMemory") + ",";
        csvfileline = csvfileline + systeminformation.get("FreeSwapSpace") + ",";
        csvfileline = csvfileline + systeminformation.get("TotalSwapSpace");

        System.out.println(csvfileline);
        writer.append(csvfileline);
        writer.flush();
        writer.close();
        isreportprinted = true;
    } catch (IOException e) {
        System.err.println("Error while writing sytem healthcheck report to csv file : "+file);
        e.printStackTrace();
    }
    return isreportprinted;
}

public static void main(String[] args) {
    MachineHealthCheckReportGeneration mm = new MachineHealthCheckReportGeneration();
    System.out.println(mm.printMachineHealthCheckReport());
}

}

Kris :
FileWriter writer = new FileWriter(file);

This line in your code, actually opens the file in overwrite mode. So everytime, existing file is overwritten with new contents. Instead , use the append mode by adding the boolean flag.

FileWriter writer = new FileWriter(file, true);

This case, the new contents will be appended to existing CSV.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=216550&siteId=1