为什么DataInputStream.readline在字符串的开头添加奇怪的字节

时间:2012-06-16 08:52:45

标签: c# java android xmlserializer readline

从C#Server发送XML并在Android Java客户端

中接收它

这就是收到的XML外观:

<?xml version="1.0" encoding="utf-8"?>.....

这是c#发送代码

// convert the class WorkItem to xml
MemoryStream memoryStream = new MemoryStream();
XmlSerializer xs = new XmlSerializer(typeof(WorkItem));
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
xs.Serialize(xmlTextWriter, p);

// send the xml version of WorkItem to client
byte[] data = memoryStream.ToArray();
clientStream.Write(data, 0, data.Length);
Console.WriteLine(" send.." + data);
clientStream.Close();

在Java中我只是这样做:

in = new DataInputStream(skt.getInputStream());
String XMlString = in.readLine();

如果我每次都从XMlString删除3个第一个字符,那么一切正常 如果可能的话,我真的想以更好的方式做到这一点

*更新添加Android java客户端

@Override
protected String doInBackground(Long... params) {

    textTopInfo.setText("Loading workitems..");

    DataOutputStream out = null;
    DataInputStream in = null;

    try {

        Socket skt = new Socket(Consts.SERVER_URL_1, Consts.SERVER_PORT_1);
        skt.setSoTimeout(10000); //10 sec timout
        out = new DataOutputStream(skt.getOutputStream());
        in = new DataInputStream(skt.getInputStream());

        // check valid user id
        String id = prefs.getString("id", "");

        if(id.equals(""))
            return "Open menu and enter User Id";

        String theString =  Consts.PUSH_GET_WORKITEM + ":" + id ;

        out.write(theString.getBytes());

        BufferedReader d = new BufferedReader
        (new InputStreamReader(skt.getInputStream()));
        String XMlString = d.readLine();

            // here I remove the BOM
        XMlString = XMlString.substring(3);

        Log.d(TAG, "GF");   

        XStream xstream = new XStream();
        xstream.alias("WorkItem", WorkItem.class);
        xstream.alias("OneItem", OneItem.class);
        pl = (WorkItem)xstream.fromXML(XMlString);

    } catch (Exception e) {

        return "cannot connect to server " + e.toString();

    }finally{
        //kill out/in
        try {
            if(out != null)
                out.close();
            if(in!=null)
                in.close(); 
        } catch (IOException e) {

        }
    }
    return "here is the list";
}

2 个答案:

答案 0 :(得分:2)

Java 1.7中不推荐使用readLine方法;来自javadocs:

的readLine() 已过时。 此方法无法将字节正确转换为字符。从JDK 1.1开始,读取文本行的首选方法是通过BufferedReader.readLine()方法。使用DataInputStream类读取行的程序可以通过替换表单的代码转换为使用BufferedReader类:      DataInputStream d = new DataInputStream(in);

使用:      BufferedReader d           = new BufferedReader(new InputStreamReader(in));

答案 1 :(得分:2)

三个初始字节是UTF8 BOM(字节排序标记)。您需要告诉Java代码使用相同的编码。