Ramesh John
Ramesh John

Reputation: 108

How to save and read Latin1 charecters in java properties file

I am trying to save Latin1 character "ÀßÖ" in test.properties file. But it storing like "\u00C0\u00DF\u00D6". But i am expecting store exact values. Any help as possible.

Upvotes: 0

Views: 429

Answers (2)

Ramesh John
Ramesh John

Reputation: 108

With JDK 1.6 can solve using below code:

Writer writer = null;
    try
    {

        Properties prop = new Properties();
        OutputStream output = null;

        output = new FileOutputStream("D:\\test1.properties");
        // set the properties value
        prop.setProperty("database", "ÀßÖ");
        prop.setProperty("dbuser", "ÀßÖ");
        prop.setProperty("dbpassword", "ÀßÖ");

        // writer = new OutputStreamWriter(output, "windows-1252");
        writer = new OutputStreamWriter(output, "UTF-8");
        // writer.append("Text");
        prop.store(writer, null);

    }
    catch (Exception e)
    {
        // errorMessage = e.getMessage();
    }

    finally
    {

        try
        {
            if (writer != null)
            {
                writer.flush();
                writer.close();
            }
        }

        catch (Exception e)
        {
        }
    }

Try let me know.

Upvotes: 0

McDowell
McDowell

Reputation: 108859

You can store using a Writer using the overloaded store(Writer,String) method but you should not.

The standard way to save/load is via an OutputStream/InputStream. Documentation for store(OutputStream,String):

This method outputs the comments, properties keys and values in the same format as specified in store(Writer), with the following differences:

  • The stream is written using the ISO 8859-1 character encoding.
  • Characters not in Latin-1 in the comments are written as \uxxxx for their appropriate unicode hexadecimal value xxxx.
  • Characters less than \u0020 and characters greater than \u007E in property keys or values are written as \uxxxx for the appropriate hexadecimal value xxxx.

If you write data using another mechanism then any application expecting the standard form will fail as this code demonstrates:

Path file = Paths.get("tmp.properties");
Properties write = new Properties();
write.put("key", "\u00C0\u00DF\u00D6");
try (Writer writer = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) {
  write.store(writer, "demo");
}
Properties read = new Properties();
try (InputStream in = Files.newInputStream(file)) {
  read.load(in);
}
if (!write.get("key").equals(read.get("key"))) {
  throw new IOException("expected: " + write.get("key") + "; got: "
      + read.get("key"));
}

If the escaping is problematic, consider using an alternative format such as JSON - JSON mandates Unicode.

Upvotes: 1

Related Questions