4

我在比较字符串时遇到了一个奇怪的问题。我从客户端向我的服务器发送一个字符串(作为字节使用getBytes())。我通过以-Dfile.encoding=UTF-8.

当我尝试对valueOf从客户端收到的字符串执行 a 以将其转换为枚举时,我注意到了这个问题。当我打印出字符串时,它们看起来完全一样。但是当我执行 a 时compareTo,我得到一个非零数字并equals返回false

我假设这是一个编码问题。不过我不太确定——当谈到使用套接字进行客户端-服务器编程时,我还是个新手。

这就是我得到的:

Waiting for connections on port 9090
Connected to client: 127.0.0.1
received command: GetAllItems
The value is |GetAllItems| (from client)
The value is |GetAllItems| (from enum)
equals: false

我究竟做错了什么?

更新

这是我从流中重构字符串的方式。也许这是我做错了什么?

byte[] commandBytes = new byte[1024];
in.read(commandBytes); //in is a BufferedInputReader
String command = new String(commandBytes);
4

3 回答 3

4

我的猜测是,由于您的缓冲区比您的字符串大,因此在重新构造的字符串中添加了空值。在 Java 中将空值嵌入字符串中是合法的(与 C 和公司不同),尽管 Java 处理它们的方式与标准 UTF-8 不同。

尝试记录读取的长度,并将该长度传递给字符串构造函数:

int bytesRead = in.read(commandBytes);
String command = new String(commandBytes, 0, bytesRead);
于 2010-10-01T17:24:16.723 回答
3

您的问题在于如何构造字符串。您正在将字节读入长度为 1024 的缓冲区,但您并没有告诉 String 构造函数只查看相关点。所以你的代码应该是......

byte[] commandBytes = new byte[1024];
int length = in.read(commandBytes); //in is a BufferedInputReader
String command = new String(commandBytes, 0, length);
于 2010-10-01T17:29:29.053 回答
2

用于java.text.Collator比较字符串。

于 2012-02-02T09:03:07.193 回答