Venyla
Venyla

Reputation: 87

How do I create a new line in a properties file using java?

I'm trying to update a properties file with java. The file should be structured like this:

IDs = \
11:22:33:44:55:66:77,\
11:22:33:44:55:66,\
1C:BA:8C:20:C5:0A

But all I get is:

IDs=11\:22\:33\:44\:55\:66\:77\:88,\\\njj\:jj\:jj\:jj\:jj\:jj\:jj\:jj,\\\n55\:55\:55\:55\:55\:55\:55\:55,\\\n

I just couldn't find out a lot about writing properties file with java and I'm completely lost. An other problem is that the ":" is escaped automatically, how can I prevent this? The code I'm using:

String str = "";
for (User u : values){
    str = str + u.getId() + ",\\"+"\n";
}
prop.setProperty("IDs", str);

Upvotes: 1

Views: 3468

Answers (2)

Jerry Z.
Jerry Z.

Reputation: 2051

Just use commons-io library, true in (sting1, file, true); is telling the function to append.

  String sting1 = "IDs = \\";
    String sting2 = "11:22:33:44:55:66:77,\\";
    String sting3 = "11:22:33:44:55:66,\\";
    String sting4 = "1C:BA:8C:20:C5:0A";

    File file = new File("{filePath}");

    FileUtils.writeStringToFile(sting1, file, true);
    FileUtils.writeStringToFile(sting2, file, true);
    FileUtils.writeStringToFile(sting3,file,true);
    FileUtils.writeStringToFile(sting4,file,true);

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691685

A backslash at the end of a line in a properties file means that the property value continues at the next line. So your property is equivalent to

IDs = 11:22:33:44:55:66:77,11:22:33:44:55:66,1C:BA:8C:20:C5:0A

That's what you should set as the property value. Unfortunately, Properties will never format it on multiple lines as you would like it to be. It will take the backslashes and \n that you store in the property as part of the property value, and will thus escape them. So all you should do is accept for the value to be on a single line, and simply set the property value to "11:22:33:44:55:66:77,11:22:33:44:55:66,1C:BA:8C:20:C5:0A".

Upvotes: 5

Related Questions