0

现在这里是用于发送字符串的 j2me mobile 的编码:

String s="hai";
try{
    String url = "btspp://001F81000250:1;authenticate=false;encrypt=false;master=false";
    StreamConnection stream = null;
    InputStream in;
    OutputStream out;
    stream = (StreamConnection) Connector.open(url);
    out=stream.openOutputStream();
    String s=tf.getString();
    byte size=(byte) s.length();
    out.write(size);
    out.write(s.getBytes());
    out.flush();
    out.close();
    stream.close();
}
catch(Exception e){
}

现在用于接收 String 的 j2se 编码:

StreamConnectionNotifier notifier=null;
try{
    String url = "btspp://localhost:"+new UUID("1101", true).toString()+";name=PCServerCOMM;authenticate=false";
    System.out.println(LocalDevice.getLocalDevice().getBluetoothAddress()+"\nCreate server by uri: " + url);
    notifier= (StreamConnectionNotifier) Connector.open(url);
    while(true){
        System.out.println("waiting....");
        StreamConnection con = notifier.acceptAndOpen();
        System.out.println("Got connection..");
        InputStream is=con.openInputStream();
        //byte b[]=new byte[40];
        /*
          while(is.available()>0){
          System.out.print((char)is.read());
          }*/
        //is.read(b, 0, 40);
        int size=is.read();
        byte b[]=new byte[size];
        is.read(b, 0, size);
        File f=new File("d://test.xml");
        FileOutputStream fo=new FileOutputStream(f);
        fo.write(b,0,b.length);
        fo.close();
        con.close();
        System.out.println(new String (b));
    }
    //printing(f);
}             catch(Exception e){
    JOptionPane.showConfirmDialog(new JFrame(), e.getMessage());
} 

我尝试了这种数据传输编码,但它不是成功的,因为当我们发送的字符串太长时,接收端就会出现问题。我该如何解决这个问题?

有没有其他方法可以将rms中的数据传输到j2se,如果有,请帮助我....请尽快回复...

4

1 回答 1

0

您在此处写入和读取的方式,只有长度不超过 255 个字符的字符串,而且在默认编码中只占用相同数量的字节,才能正确写入。

在写作方面:

  1. 该语句byte size=(byte) s.length();以字节为单位转换字符串的长度,因此只取长度的低 8 位。因此,只有最多 255 的长度是正确的。
  2. 然后你将字符串转换为一个字节数组s.getBytes()- 这个数组可能比原始字符串长(以字节为单位)。此转换使用发送设备的默认编码。

在阅读方面:

  1. 该语句int size=is.read();读取之前写入的长度,然后您正在创建一个字节数组。
  2. is.read(b, 0, size);将一些字节读入此数组 - 它不一定会填充完整的数组。
  3. 然后,您将使用接收设备的默认编码将您的字节数组(甚至可能没有完全填充)转换为字符串。

所以,我们有:

  1. 所有超过 255 个字符的字符串都写错了。
  2. 如果发送方和接收方使用不同的编码,您可能会得到错误的输出。
  3. 如果发送方使用 UTF-8 之类的编码,其中某些字符占用超过一个字节,则字符串在末尾被截断(如果出现此类字符)。

如何解决这个问题:

  • 如果您可以在两侧使用 DataInputStream 和 DataOutputStream(我对 J2ME 一无所知),请在此处使用它们以及它们的readUTFwriteUTF方法。它们解决了您的所有问题(如果您的字符串在此处使用的修改后的 UTF-8 编码中最多占用 65535 个字节)。
  • 如果不:
    • 决定字符串的长度,并用正确的字节数对长度进行编码。每个 Java 字符串 4 个字节就足够了。
    • 在转换为 byte[] 之后测量长度,而不是之前。
    • 使用循环读取数组,以确保捕获整个字符串。
    • 对于getBytes()and new String(...),使用带有显式编码名称的变体并给它们相同的编码(我推荐"UTF-8")。
于 2011-03-05T17:11:40.450 回答