0

在远程 http 服务器上,我在 Sublime text2 中创建 test.xml 文件,并使用编码 utf-8 保存它。

<?xml version='1.0' encoding='Utf-8' ?>
<Shops>
 <Shop name="one"></Shop>
 <Shop name="two" ></Shop>
 <Shop name="three"></Shop>
</Shops>

然后我将它下载到我的设备上:

String str="";
            URL url = new URL(Server+urls);
            URLConnection ucon = url.openConnection();
            InputStream is = ucon.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            ByteArrayBuffer baf = new ByteArrayBuffer(50);
            int current = 0;
            while ((current = bis.read()) != -1) 
            {
                baf.append((byte) current);
            }
            str = new String(baf.toByteArray(),"Utf-8");
            DataOutputStream out = null;
            out = new DataOutputStream(openFileOutput(filename, Context.MODE_PRIVATE));
            out.writeUTF(str);
            out.close();

之后,我通过 DDMS 文件资源管理器将其下载到我的 macbook 上,在 Sublime text2 中打开,然后看到:

008e 3c3f 786d 6c20 7665 7273 696f 6e3d
2731 2e30 2720 656e 636f 6469 6e67 3d27
5574 662d 3827 203f 3e0d 0a3c 5368 6f70
733e 0d0a 203c 5368 6f70 206e 616d 653d
226f 6e65 223e 3c2f 5368 6f70 3e0d 0a20
3c53 686f 7020 6e61 6d65 3d22 7477 6f22
203e 3c2f 5368 6f70 3e0d 0a20 3c53 686f
7020 6e61 6d65 3d22 7468 7265 6522 3e3c
2f53 686f 703e 0d0a 3c2f 5368 6f70 733e

然后我选择使用编码 utf-8 重新打开,并看到(顺便说一句,我无法复制/过去我看到的内容):

在此处输入图像描述

4

2 回答 2

0

我不太确定您为什么要从/转换为字节,但这个问题可能是StAX的一个很好的候选者。

查看阅读和写作部分。

于 2013-01-17T15:37:08.340 回答
0

.writeUTF使用修改后的 UTF-8,而不是 UTF-8。

XML的0x00 0x8e长度是 142 的大端无符号短,并且与 142 的实际长度相匹配。

用这个:

str = new String(baf.toByteArray(),"UTF-8");
OutputStreamWriter osw = new OutputStreamWriter(
    openFileOutput(filename, Context.MODE_PRIVATE),
    Charset.forName("UTF-8").newEncoder()
);
osw.write(str);
于 2013-01-17T16:48:12.563 回答