class UnicodeUtil {

    public static byte[] convert(final byte[] bytes, final String desiredOutputEncoding) throws IOException {
        // Workaround for bug that will not be fixed by SUN
        // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4508058
        UnicodeInputStream uis = new UnicodeInputStream(new ByteArrayInputStream(bytes), "ASCII");
        boolean unicodeOutputReqd = (getBOM(desiredOutputEncoding).equals("")) ? false : true;
        String enc = uis.getEncoding();
        String BOM = getBOM(enc); // get the BOM of the inputstream

        if ("".equals(BOM)) {
            // inputstream looks like ascii...
            // create a BOM based on the outputstream
            BOM = getBOM(desiredOutputEncoding);
        }
        uis.close();

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(bytes,
                uis.getBomOffset(), bytes.length), enc));
        Writer w = new BufferedWriter(new OutputStreamWriter(out, desiredOutputEncoding));

        // dont write a BOM for ascii(out) as the OutputStreamWriter
        // will not process it correctly.
        if (!"".equals(BOM) && unicodeOutputReqd) {
            w.write(BOM);
        }

        char[] buffer = new char[4096];
        int len;
        while (true) {
            len = br.read(buffer);
            if (len == -1) {
                break;
            }
            w.write(buffer, 0, len);
        }

        br.close(); // Close the input.
        w.close(); // Flush and close output.
        return out.toByteArray();
    }

}