1

I want to create One file with .cfg extension and content of this file must be in below format

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
}

For this I am using below code

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

But problem is that when I run this, my file is created with empty data. So please help me to fix this issue.

I am using Java with Eclipse Mars 1.

Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
user3441151
  • 1,880
  • 6
  • 35
  • 79
  • 5
    Use the try-with-resources statement to make sure you **always** close your writer. – JB Nizet Jan 09 '17 at 07:36
  • 2
    Did you try flushing the writer? – Mureinik Jan 09 '17 at 07:36
  • 1
    Did you notice that your Eclipse told you about the problem in a warning? – Holger Jan 09 '17 at 10:24
  • @Holger Can I check my file is exist or not? – user3441151 Jan 09 '17 at 11:29
  • 1
    Sure, and I suppose, if you look into the documentation, you’ll find out how to do that. But where’s the connection to my previous comment that causes you to ask *me*? – Holger Jan 09 '17 at 11:31
  • @Holger Thank you. But this query has been resolved. – user3441151 Jan 09 '17 at 11:40
  • @Holger I already mark answer. – user3441151 Jan 09 '17 at 11:41
  • 1
    That doesn’t stop people from posting further notes, like that if you cared about the warnings of your IDE, most notably the one telling you that you should close resources, you never had the problem in the first place. Regardless of whether you accepted the answer or not, it’s a poor answer, as you should follow [JB Nizet’s advice](http://stackoverflow.com/questions/41543016/java-bufferedwriter-file-content-is-empty?noredirect=1#comment70290732_41543016) and use [the try-with-resources statement](https://docs.oracle.com/javase/8/docs/technotes/guides/language/try-with-resources.html) instead. – Holger Jan 09 '17 at 11:55
  • @Holger If I remove writer.flush(); writer.close(); than I did not get any warning in my Eclipse Mars 1. – user3441151 Jan 09 '17 at 13:50
  • 1
    Check your [settings. The default is to warn you](http://help.eclipse.org/neon/topic/org.eclipse.jdt.doc.user/reference/preferences/java/compiler/ref-preferences-errors-warnings.htm#resource-leak). See also [“Avoiding resource leaks”](http://help.eclipse.org/neon/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Ftasks%2Ftask-avoiding_resource_leaks.htm)… – Holger Jan 09 '17 at 13:55
  • @Holger Yes you right. I resolved my issue by using "try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(propFile.getProperty(Constants.filepath) + filename + ".cfg"))) { .... }" – user3441151 Jan 09 '17 at 14:39
  • @Holger I think that is the correct answer as you suggest me. Right? – user3441151 Jan 09 '17 at 14:41

1 Answers1

2

You need to flush and close the writer by

writer.flush();
writer.close();
Aimee Borda
  • 842
  • 2
  • 11
  • 22