Removes a windows byte order mark if present in XML String. - Java XML

Java examples for XML:XML Encoding

Description

Removes a windows byte order mark if present in XML String.

Demo Code

/* See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * Esri Inc. licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.//from  w w  w .  j a v a2 s  .co m
 */
//package com.java2s;

import java.io.UnsupportedEncodingException;

public class Main {
    public static void main(String[] argv) throws Exception {
        String s = "java2s.com";
        System.out.println(removeBOM(s));
    }

    /**
     * Removes a windows byte order mark if present.
     * @param s the string to check
     * @return the string absent the byte order mark
     */
    public static String removeBOM(String s) {
        if (s != null) {
            byte[] bom = new byte[3];
            bom[0] = (byte) 0xEF;
            bom[1] = (byte) 0xBB;
            bom[2] = (byte) 0xBF;
            try {
                String sbom = new String(bom, "UTF-8");
                s = s.trim();
                if (s.startsWith(sbom)) {
                    s = s.substring(1).trim();
                }
            } catch (UnsupportedEncodingException e) {
            }
        }
        return s;
    }
}

Related Tutorials