简体   繁体   English

如何在属性文件中包含“#”。 '\\#'转义不起作用

[英]How to include “#” in properties file. '\#' escape doesn't work

I need to include value with # in properties file but # is used to comment line in properties file. 我需要在属性文件中的#中包含值,但#用于在属性文件中注释行。 How to I do it. 我该怎么做。

I want to define mapping something as follow 我想定义映射如下

someField[#]=someValue

But anything after # get commented. 但是#之后的所有内容都会发表评论。 Thanks for help. 感谢帮助。

You can escape the # with \\ , like 您可以使用\\转义# ,例如

someField\#=1

which will get you {someField#=1} 这将使您{someField#=1}

write it like this : 这样写:

key\#1=value\#1

other special characters like '=', ':' work the same. 其他特殊字符(例如'=',':')的作用相同。

Code in Java: Java代码:

  1. write properties: 写属性:

     Properties p = new Properties(); p.load(PropertiesTest.class.getResourceAsStream("prop.properties")); p.setProperty("key#=dsafw", "value $#@^$%@**^"); p.setProperty("key#1", "value#1"); p.store(new FileOutputStream(new File("../TEMP/prop.properties")), "write special property kvs"); 
  2. read properties: 读取属性:

     p.load(new FileInputStream(new File("../TEMP/prop.properties"))); Enumeration<Object> keys = p.keys(); while(keys.hasMoreElements()){ String key = (String) keys.nextElement(); System.out.println("key --> " + key + ", value --> " + p.getProperty(key)); } 

Tested on Java 8 works fine without any escape character 在Java 8上经过测试,可以正常运行,没有任何转义符

Example below 下面的例子

properties 属性

name# = #John#

Java code Java代码

System.out.println( p.getProperty("name#"));

Prints: #John# 印刷品: #John#

Edit: 编辑:

If the key contains the first character as # in that case you need to escape it with '\\' in properties file 如果键包含第一个字符(如#),则需要在属性文件中使用'\\'对其进行转义

eg 例如

\#country# = #India#

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

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