Javaを使用して、定期的にCSVファイルにレコードを書き込みます

ランジート:

私は(私は同じのためにcronジョブを使用することを計画しています)と、CSVファイル内の同じ格納し、定期的にサーバーの健康情報を取得しようとしています。問題は、コードの店の下に一つだけライン.IEだけ最新のレコードが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に追加されます。

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=276221&siteId=1