以字节为单位的字符串无法转换为等效的字符串

时间:2017-10-25 05:40:10

标签: java arrays byte

val conf = new SparkConf(true).set("spark.cassandra.connection.host","192.168.xx.xxx").set("spark.cassandra.auth.username","test").set("spark.cassandra.auth.password","test")
val sc = new SparkContext(conf)
var ctable = sc.cassandraTable("A", "B").select("id1","id2","timing","value").where("id1=?","1001")

我注意到了

1)我使用getByte()方法获得的字节数组是不同的。

2)即使a和b的字符串(来自代码)完全相同,但它们并不相等。

以下是我从四个打印语句中得到的输出:

public class MyClass{
static final String BROADCAST = "Broadcasting";
public static final int PORT = 12344;
public static String host = "localhost";
public static void main(String[] args) {
    // TODO Auto-generated method stub
    DatagramSocket serverSocket;
    try {
        serverSocket = new DatagramSocket(PORT);
        InetAddress addr = InetAddress.getByName(host);

        byte[] sendData = BROADCAST.getBytes();

        DatagramPacket sendPacket = new DatagramPacket(
                sendData, //data byte array
                sendData.length, //number of bytes
                addr, //destination host address
                PORT); //destination port
        serverSocket.send(sendPacket);
        byte[] rcvData = new byte[1024];

        DatagramPacket rcvPacket = new DatagramPacket(
                rcvData, rcvData.length);

        //packet gets filled in by receive
        serverSocket.receive(rcvPacket);

        //Why the two Strings are not the same?
        //Why the bytes derived from the same string different?
        byte[] a = rcvData;
        byte[] b= BROADCAST.getBytes();
        System.out.println(a.equals(b));
        System.out.println(new String(a));
        System.out.println(new String(b));
        System.out.println((new String(a).equals(new String(b))));


    } catch (SocketException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
}

3 个答案:

答案 0 :(得分:1)

您的接收代码不正确,因为传入的数据包并不总是与接收缓冲区的大小相同。因此,您需要在将数据转换为String时限制数据的长度,否则,您还将转换垃圾。

byte[] a = rcvData;
byte[] b = BROADCAST.getBytes();
String recStr = new String(rcvData, 0, rcvPacket.getLength());
System.out.println(recStr.equals(new String(b)));

然后,您确实正在比较发送和接收数据包内容。

答案 1 :(得分:0)

您的代码存在问题

第一

您的密码:

byte[] rcvData = new byte[1024];

它应该:(如果它不是功能要求)

byte[] rcvData = new byte[BROADCAST.getBytes().length];

第二

您的代码:

System.out.println(a.equals(b));

它应该:

System.out.println(Arrays.equals(a,b));

答案 2 :(得分:-1)

我认为在 trim()的帮助下,你可以实现你所期望的。可以是字节a和b是不同大小使用trim()同时将字节转换为字符串

        byte[] a = rcvData;
        byte[] b= BROADCAST.getBytes();    
        System.out.println(new String(a).trim());
        System.out.println(new String(b).trim());
        System.out.println((new String(a).trim().equals(new String(b).trim())));
相关问题