Периодическая запись записей в файл CSV с использованием Java - PullRequest
0 голосов
/ 12 марта 2020

Я пытаюсь периодически получать информацию о работоспособности сервера (я планирую использовать для нее задание cron) и сохраняю его в файле CSV. Проблема в том, что в приведенном ниже коде хранится только одна строка. Т.е. в CSV-файле хранится только последняя запись, а предыдущая запись удаляется. Согласно моему требованию, файл CSV должен содержать записи для каждого выполнения ниже java кода.

Нужна помощь, чтобы решить проблему. Я не должен использовать Maven или любые внешние банки для этого требования.

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

}

1 Ответ

1 голос
/ 12 марта 2020
FileWriter writer = new FileWriter(file);

Эта строка в вашем коде фактически открывает файл в режиме перезаписи. Поэтому каждый раз существующий файл перезаписывается новым содержимым. Вместо этого используйте режим добавления, добавив логический флаг.

FileWriter writer = new FileWriter(file, true);

В этом случае новое содержимое будет добавлено к существующему CSV.

...