转义 - 从 Java 属性读取时的字符

Escaping - character when reading from Java properites

我正在尝试从 Java 属性文件中读入一个 - 值,但它一直给我值 â 和类似于 epsilon 的东西(粘贴时遇到问题)

我没有逃避 " 的问题,但似乎无论我做什么 - 都会给我带来问题。我已经尝试过 '-' 和 \- 和 \\- 但似乎没有任何效果。

@Test
public void readFromProperties() throws IOException {
    Properties options = new Properties();

    FileInputStream in = new FileInputStream(Configs.optionsFi);
    negComments.load(in);
    in.close();

    String option = options.getProperty("OPTION8");
    System.out.println(negComment);
}

属性文件:

OPTION8=asdf asdf asdf asdf asdf – \"asdfasdf\"

System.out.println 结果:

asdf asdf asdf asdf asdf âepsilonlikething "asdfasdf"

属性 文件中的 字符不是普通破折号 ('HYPHEN-MINUS' (U+002D)), but an 'EN DASH' (U+2013).

load(InputStream inStream) 的文档明确指定:

The input stream is in a simple line-oriented format as specified in load(Reader) and is assumed to use the ISO 8859-1 character encoding; that is each byte is one Latin1 character.

您的 属性 文件是 UTF-8,所以您遇到了字符编码错误。

有 3 种方法可以解决问题:

  1. 假设您想要一个普通破折号,请将 替换为 -
    并确保将文件保存在 ISO 8859-1 又名 Latin1 又名 Windows-1252.

  2. 对字符进行编码,即将替换为\u2013
    并确保将文件保存在 ISO 8859-1 又名 Latin1 又名 Windows-1252.

  3. 使用UTF-8读取文件:

    try (BufferedReader in = Files.newBufferedReader(Paths.get(Configs.optionsFi))) {
        options.load(in);
    }