使用 Java 定期将记录写入 CSV 文件

Writing records to CSV file periodically using Java

我正在尝试定期获取服务器健康信息(我计划为此使用 cron 作业)并将其存储在 CSV 文件中。问题是,下面的代码只存储一行。即只有最新记录存储在 CSV 文件中,以前的记录被删除。根据我的要求,CSV 文件应包含每次执行以下 java 代码的记录。

需要帮助来解决问题。我不应该为此要求使用 Maven 或任何外部 jar。

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());
}

}

FileWriter writer = new FileWriter(file);

您代码中的这一行实际上是以覆盖模式打开文件。所以每次,现有文件都会被新内容覆盖。相反,通过添加布尔标志使用追加模式。

FileWriter writer = new FileWriter(file, true);

这种情况下,新内容将附加到现有 CSV 中。