X-Git-Url: https://gitweb.fperrin.net/?p=GpsPrune.git;a=blobdiff_plain;f=tim%2Fprune%2Fsave%2Fxml%2FXmlUtils.java;h=dc8284c30ea90d4586b0cdec70c72c6102346225;hp=a4f9caec11704a46dcd56fe3d22bde4922a49f09;hb=88f2c3647ed9e055090484f01a959d4581f85e7d;hpb=326f489e36aa7f235bc19409a57bf4955cd50f24 diff --git a/tim/prune/save/xml/XmlUtils.java b/tim/prune/save/xml/XmlUtils.java index a4f9cae..dc8284c 100644 --- a/tim/prune/save/xml/XmlUtils.java +++ b/tim/prune/save/xml/XmlUtils.java @@ -1,5 +1,11 @@ package tim.prune.save.xml; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.nio.charset.Charset; + /** * Collection of utility functions for handling XML */ @@ -9,6 +15,8 @@ public abstract class XmlUtils private static final String CDATA_START = ""; + /** Cached copy of system encoding string */ + private static String _systemEncoding = null; /** * Fix the CDATA blocks in the given String to give valid xml @@ -34,4 +42,68 @@ public abstract class XmlUtils } return CDATA_START + result + CDATA_END; } + + + /** + * @return true if system uses UTF-8 by default + */ + public static boolean isSystemUtf8() + { + String systemEncoding = getSystemEncoding(); + return (systemEncoding != null && systemEncoding.toUpperCase().equals("UTF-8")); + } + + /** + * @return name of the system's character encoding + */ + public static String getSystemEncoding() + { + if (_systemEncoding == null) { + _systemEncoding = determineSystemEncoding(); + } + return _systemEncoding; + } + + /** + * Use a temporary file to obtain the name of the default system encoding + * @return name of default system encoding, or null if write failed + */ + private static String determineSystemEncoding() + { + File tempFile = null; + String encoding = null; + try + { + tempFile = File.createTempFile("gpsprune", null); + OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(tempFile)); + encoding = getEncoding(writer); + writer.close(); + } + catch (IOException e) {} // value stays null + // Delete temp file + if (tempFile != null && tempFile.exists()) { + if (!tempFile.delete()) { + System.err.println("Cannot delete temp file: " + tempFile.getAbsolutePath()); + } + } + // If writing failed (eg permissions) then just ask system for default + if (encoding == null) encoding = Charset.defaultCharset().name(); + return encoding; + } + + + /** + * Get the default system encoding using a writer + * @param inWriter writer object + * @return string defining encoding + */ + public static String getEncoding(OutputStreamWriter inWriter) + { + String encoding = inWriter.getEncoding(); + try { + encoding = Charset.forName(encoding).name(); + } + catch (Exception e) {} // ignore failure to find encoding + return encoding; + } }