日期:2014-05-20  浏览次数:20722 次

j2me socket读取服务器中文出乱码
conn = (SocketConnection) Connector.open(addr ,Connector.READ_WRITE);
conn.setSocketOption(SocketConnection.KEEPALIVE, 100);
is = conn.openInputStream();
os = conn.openOutputStream();

int i = is.available();
String str = ""; 
byte[] bstr = new byte[i];
try{
  is.read(bstr);

 str=new String(bstr,"UTF-8"); ///////////////问题在这里,我转UTF8的时候报错说 转码错误是怎么回事啊?
}catch(Exception e)
{
}
 

请各位帮忙下, 若是我的读取服务器方式错误的话 希望大家指点下, 若我不转UTF8的话 在手机上又是乱码,很急,请各位帮忙 谢谢!!!!

------解决方案--------------------
Java code

/**
     * 读流生成byte[],全读取
     * 
     * @param is
     * @return
     */
    public static byte[] readFully(InputStream is) {
        byte[] bytes = null;
        if (is != null) {
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                int l = 0;
                byte[] b = new byte[1024];
                while ((l = is.read(b)) != -1) {
                    baos.write(b, 0, l);
                }
                bytes = baos.toByteArray();
                baos.close();
                baos = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return bytes;
    }

------解决方案--------------------
ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
System.out.println("baos=="+baos);

这时候还没往里头写数据呢,当然是空的...
你要根据返回的byte[]是不是空来判断有没有数据

------解决方案--------------------
byte[] bstr=readFully(is);
str=new String(bstr,"UTF-8"); 
System.out.println("str=="+str);