使用Java定期将记录写入CSV文件
我正在尝试定期获取服务器运行状况信息(我计划使用cron作业来获取相同的信息),并将其存储在CSV文件中。问题是,下面的代码只存储一行。只有最新记录存储在CSV文件中,以前的记录将被删除。根据我的要求,CSV文件应包含以下java代码每次执行的记录 需要帮助来解决这个问题。对于这个需求,我不应该使用Maven或任何外部jar使用Java定期将记录写入CSV文件,java,csv,export-to-csv,Java,Csv,Export To Csv,我正在尝试定期获取服务器运行状况信息(我计划使用cron作业来获取相同的信息),并将其存储在CSV文件中。问题是,下面的代码只存储一行。只有最新记录存储在CSV文件中,以前的记录将被删除。根据我的要求,CSV文件应包含以下java代码每次执行的记录 需要帮助来解决这个问题。对于这个需求,我不应该使用Maven或任何外部jar public class MachineHealthCheckReportGeneration { private final String environmentnam
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());
}
公共类MachineHealthCheckReportGeneration{
私有最终字符串environmentname=“DEV”;
私有最终字符串applicationname=“XYZ”;
私有最终字符串username=System.getProperty(“user.name”);//不要更改此行中的任何内容
私有最终字符串csvfiledir=“D:\\logs\\monitoring\\server\\”+environmentname;
私有映射系统信息=null;
///请勿在此行之后编辑///
私有映射getMachineHealthCehckReport(){
systeminformation=newhashmap();
OperatingSystemMXBean osbean=ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class);
systeminformation.put(“Application”,applicationname);
systeminformation.put(“CaptureTime”,Instant.now().toString());
试一试{
systeminformation.put(“主机名”,InetAddress.getLocalHost().getHostName());
}捕获(未知后异常e){
System.err.println(“未能获取主机名…”);
e、 printStackTrace();
}
试一试{
systeminformation.put(“IPAddress”,InetAddress.getLocalHost().getHostAddress());
}捕获(未知后异常e){
System.err.println(“无法获取IP地址…”);
e、 printStackTrace();
}
systeminformation.put(“CPUCount”,Long.toString(osbean.getAvailableProcessor());
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(新文件(“D:\\logs”).getFreeSpace()/(1024*1024*1024))+“GB”);
systeminformation.put(“D:\\config”,
Long.toString(新文件(“D:\\config”).getFreeSpace()/(1024*1024*1024))+“GB”);
System.out.println(系统信息);
返回系统信息;
}
受保护的布尔printMachineHealthCheckReport(){
字符串csvfileline=null;
布尔值isreportprinted=false;
//创建csv文件目录和文件(如果不存在)
文件目录=新文件(String.valueOf(csvfiledir));
File File=新文件(String.valueOf(csvfiledir++“/”+systeminformation.get(“HostName”)+“.csv”);
如果(!directory.exists()){
mkdirs()目录;
如果(!file.exists()){
试一试{
createNewFile();
}捕获(IOE异常){
System.err.println(“未能创建文件:+文件”);
e、 printStackTrace();
}
}
}
试一试{
FileWriter writer=新的FileWriter(文件);
//如果文件为空,则插入头
如果(file.length()==0){
writer.append(
“应用程序、CaptureTime、主机名、IPAddress、CPUCount、SystemCPULoad、ProcessCPULoad、ProcessCPUTime、FreePhysicalMemory、TotalPhysicalMemory、CommittedVirtualMemory、FreeSwapSece、TotalSwapSpace”);
}
csvfileline=“\r\n”+systeminformation.get(“应用程序”)+,”;
csvfileline=csvfileline+systeminformation.get(“CaptureTime”)+;
csvfileline=csvfileline+systeminformation.get(“主机名”)+;
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;
}捕获(IOE异常){
System.err.println(“将系统健康检查报告写入csv文件时出错:“+文件”);
e、 printStackTrace();
}
返回报告打印;
}
公共静态void main(字符串[]args){
MachineHealthCheckReportGeneration mm=新的MachineHealthCheckReportGeneration();
System.out.println(mm.printMachineHealthCheckReport());
}
}
代码中的这一行实际上以覆盖模式打开文件。所以每次,现有文件都会被新内容覆盖。相反,通过添加bo来使用追加模式
FileWriter writer = new FileWriter(file);
FileWriter writer = new FileWriter(file, true);