Xstream is the right way to save XML in UTF-8

Previously, to read UTF-8 encoded XML through xstream, I use DomDriver as follows:

XStream xStream = new XStream(new DomDriver("UTF-8"));

However, later I understand that it is very slow. I am using the following method:

Optimize xstream download speed

It works as a minimum.

However, later I understand that the same method cannot be used to write XML. Will I get everything ??? characters.

This is the last working code using DomDriver while writing

public static boolean toXML(Object object, File file) {
    XStream xStream = new XStream(new DomDriver("UTF-8"));
    OutputStream outputStream = null;

    try {
        outputStream = new FileOutputStream(file);
        xStream.toXML(object, outputStream);
    }
    catch (Exception exp) {
        log.error(null, exp);
        return false;
    }
    finally {
        if (false == close(outputStream)) {
            return false;
        }
        outputStream = null;
    }

    return true;
}

The above code is working fine. To fit the read method , which does not use DomDriver, I change the code to

public static boolean toXML(Object object, File file) {
    XStream xStream = new XStream();
    OutputStream outputStream = null;
    Writer writer = null;

    try {
        outputStream = new FileOutputStream(file);
        writer = new OutputStreamWriter(outputStream, Charset.forName("UTF-8"));
        xStream.toXML(object, outputStream);
    }
    catch (Exception exp) {
        log.error(null, exp);
        return false;
    }
    finally {
        if (false == close(writer)) {
            return false;
        }
        if (false == close(outputStream)) {
            return false;
        }
        writer = null;
        outputStream = null;
    }

    return true;
}

This time all my Chinese characters will change to

Can I find out everything that I did wrong?

+3
1

:

outputStream = new FileOutputStream(file);
writer = new OutputStreamWriter(outputStream, Charset.forName("UTF-8"));
xStream.toXML(object, outputStream);

, UTF-8, !

:

xStream.toXML(object, writer);

:

  • ; if (foo) if (!foo)
  • Exception - ; .
  • Java; , - ,
  • close , close, , , , . (, OutputStreamWriter` , .)
  • null
+11

Source: https://habr.com/ru/post/1763240/


All Articles