我想创建一个带有 .cfg 扩展名的文件,此文件的内容必须采用以下格式
define host {
host_name test.testing.local
alias Server 1
address 192.168.1.111
check_command check-host-alive
max_check_attempts 10
check_interval 5
retry_interval 5
active_checks_enabled 1
passive_checks_enabled 1
check_period 24x7
register 1
}
为此我使用下面的代码
@POST
@Consumes("application/x-www-form-urlencoded")
@Path("/addNewHost")
public Response AddNewHost(String json) {
JSONObject returnJson = new JSONObject();
try {
JSONObject innerJsonObj = new JSONObject(json);
HostObj hostObj = new HostObj();
hostObj.hostname = innerJsonObj.getString("hostname");
hostObj.ipaddress = innerJsonObj.getString("ipaddress");
hostObj.alias = innerJsonObj.getString("alias");
hostObj.check_command = innerJsonObj.getString("check_command");
hostObj.notification_period = innerJsonObj.getString("notification_period");
hostObj.max_check_attempts = innerJsonObj.getInt("max_check_attempts");
hostObj.active_checks_enabled = innerJsonObj.getInt("active_checks_enabled");
hostObj.passive_checks_enabled = innerJsonObj.getInt("passive_checks_enabled");
hostObj.register = innerJsonObj.getBoolean("register");
hostObj.chIntervalInMinutes = innerJsonObj.getInt("chIntervalInMinutes");
hostObj.retryIntervalInMinutes = innerJsonObj.getInt("retryIntervalInMinutes");
hostObj.contact_groups = innerJsonObj.getString("contact_groups");
hostObj.check_period = innerJsonObj.getString("check_period");
String filename = hostObj.ipaddress.replace(".", "");
Properties propFile = LoadProp.getProperties();
BufferedWriter writer = Files.newBufferedWriter(Paths.get(propFile.getProperty(Constants.filepath) + filename + ".cfg"));
writer.write("define host {\n");
writer.write("\thost_name\t" + hostObj.hostname + "\n");
writer.write("\talias\t" + hostObj.alias + "\n");
writer.write("\taddress\t" + hostObj.ipaddress + "\n");
writer.write("\tcheck_command\t" + hostObj.check_command + "\n");
writer.write("\tmax_check_attempts\t" + hostObj.max_check_attempts + "\n");
writer.write("\tcheck_interval\t" + hostObj.chIntervalInMinutes + "\n");
writer.write("\tretry_interval\t" + hostObj.retryIntervalInMinutes + "\n");
writer.write("\tactive_checks_enabled\t" + hostObj.active_checks_enabled + "\n");
writer.write("\tpassive_checks_enabled\t" + hostObj.passive_checks_enabled + "\n");
writer.write("\tcheck_period\t" + hostObj.check_period + "\n");
writer.write("\tregister\t" + hostObj.register + "\n}");
returnJson.put("success", true);
} catch (Exception e) {
JSONObject errorJson = new JSONObject();
errorJson.put("success", false);
errorJson.put("error", errorMsg);
return Response.ok(errorJson.toString()).header("Access-Control-Allow-Origin", "*").build();
}
return Response.ok(returnJson.toString()).header("Access-Control-Allow-Origin", "*").build();
}
但问题是,当我运行它时,我的文件是用空数据创建的。 所以请帮我解决这个问题。
我将Java
与Eclipse Mars 1
一起使用。
答案 0 :(得分:1)
您需要通过
刷新并关闭编写器writer.flush();
writer.close();