简体   繁体   English

如何使用Java在属性文件中创建换行?

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

I'm trying to update a properties file with java. 我正在尝试使用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. 我只是找不到很多关于用Java编写属性文件的信息,我完全迷失了。 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);

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. 不幸的是,Properties永远不会像您希望的那样在多行上设置其格式。 It will take the backslashes and \\n that you store in the property as part of the property value, and will thus escape them. 将存储在属性中的反斜杠和\\ n作为属性值的一部分,从而可以将它们转义。 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" . 因此,您所要做的就是接受该值在一行中,然后只需将属性值设置为"11:22:33:44:55:66:77,11:22:33:44:55:66,1C:BA:8C:20:C5:0A"

Just use commons-io library, true in (sting1, file, true); 只需使用commons-io库, true(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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM