farnett
farnett

Reputation: 480

Escaping - character when reading from Java properites

I'm trying to read in a - value from a Java properties file, but it keeps giving me the value â and something like an epsilon (having issues pasting it)

I have no issues escaping the " but it seems like no matter what I do - is giving me issues. I've tried '-' and \- and \\- but nothing seems to be working.

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

properties file:

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

System.out.println result:

asdf asdf asdf asdf asdf âepsilonlikething "asdfasdf"

Upvotes: 0

Views: 711

Answers (1)

Andreas
Andreas

Reputation: 159106

The character in the property file is not a normal dash ('HYPHEN-MINUS' (U+002D)), but an 'EN DASH' (U+2013).

Documentation of load(InputStream inStream) explicitly specifies:

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.

Your property file is in UTF-8, so you get that character encoding error.

There are 3 ways to fix the problem:

  1. Assuming that you intended a normal dash, replace the with a -,
    and make sure you save the file in ISO 8859-1 aka Latin1 aka Windows-1252.

  2. Encode the character, i.e. replace with \u2013,
    and make sure you save the file in ISO 8859-1 aka Latin1 aka Windows-1252.

  3. Read the file using UTF-8:

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

Upvotes: 2

Related Questions