D
D
dikium2016-12-12 15:46:19
Java
dikium, 2016-12-12 15:46:19

How to fix encoding when saving xml file in Java?

Hello brothers! Today I stumbled upon an incomprehensible problem. I migrated my Java project from maven to graddle. And everything is fine, but for some reason XML files are saved in the wrong encoding... When you save them in UTF-8, this is what happens:

<?xml version="1.0" encoding="utf-8"?>
<sky>
  <mechanism name="33">
    <abilities>
      <ability name="�����������1" />
      <ability name="22" />
    </abilities>
  </mechanism>
</sky>

And when saving in windows-1251, this is:
<?xml version="1.0" encoding="windows-1251"?>
<sky>
  <mechanism name="33">
    <abilities>
      <ability name="Проверка" />
      <ability name="22" />
    </abilities>
  </mechanism>
</sky>

These files are automatically generated by my program using this method:
public void save(String path) throws IOException
  {
    Document document = new Document();
    document.setRootElement(getXMLElement());

    XMLOutputter outputter = new XMLOutputter();
    outputter.setFormat(Format.getPrettyFormat().setEncoding("windows-1251")); //utf-8 здесь работает неверно
    outputter.output(document, new FileWriter(path));
  }

Those. when saving in windows-1251, everything is fine, but with utf-8 - krakozyabry. This was not the case before. At first I thought that the library for parsing XML is crooked. I used dom4j. But then I switched to jdom2 and the situation remained the same. The file saved by the program cannot be opened by the program. However, if you manually fix the xml file, then everything is fine. I suspect that although the encoding is set to utf-8, the program still writes in windows-1251. Apparently the problem is somewhere in the project settings, but where - I'll never know. I am using Intellij IDEA. Help me please!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
nikola_sa, 2016-12-13
@dikium

look at stackoverflow.com/a/9853261/3331243

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question