문제

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.

도움이 되었습니까?

해결책

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top