繁体   English   中英

如何通过蓝牙将rms(j2me)中的记录传输到j2se

[英]how to transfer the records in rms(j2me) to j2se through bluetooth

现在,这里是用于发送字符串的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){
}

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

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,如果可以,请帮助我....请快速回复...

您在此处读写的方式只能正确写出最多255个字符的字符串,而且这些字符串在默认编码中仅占用相同数量的字节。

在写作方面:

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

在阅读方面:

  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()new String(...) ,请使用具有显式编码名称并为其提供相同编码的变体(我建议使用"UTF-8" )。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM