string.equal 方法无效
string.equal method not working
我是 java 的新手。我现在的问题是我正在从客户端向服务器发送文件名。当我在服务器中打印该文件名时,它打印正常,但与我硬编码的字符串不匹配。例如:我将 'Lecture.pdf' 作为文件名从客户端发送到服务器,然后我将接收到的文件名与硬编码字符串 'Lecture.pdf' 进行匹配,它不会匹配并最终 return 为假。我希望 equal 方法 return true(应该如此)。
这是一个可能会说明问题的代码片段。 'server' 是这里的 Socket 对象,我正在使用字节数组读取文件名:
InputStream is = null;
byte response [] = new byte [50];
is = server.getInputStream();
is.read(response);
String str_res = new String (response);
System.out.println ("Got reS: " + str_res);
System.out.println ( "Result: "+(response.toString()).equals ("Lecture.pdf"));
你需要写
new String(response, "UTF-8").equals ("Lecture.pdf")
或
str_res.equals("Lecture.pdf")
您将原始的、未转换的字节数组等同于字符串。字节数组永远不会等于字符串,因为它们是不同的类型。您还应该检查转换的字节数是否正确——如果您发送 1 个字节,您的输出字符串应该有多少个字符?查看 public String(byte[] bytes, int offset, int length, Charset charset) 构造函数,并跟踪您实际读取的字节数:
int bytesRead = is.read(response);
不是将 response.toString() 与硬编码值进行比较,而是比较 str_res.
response.toString()是字节数组的字符串表示。
变化:
System.out.println ( "Result: "+(response.toString()).equals ("Lecture.pdf"));
收件人:
System.out.println ( "Result: "+str_res.equals ("Lecture.pdf"));
我是 java 的新手。我现在的问题是我正在从客户端向服务器发送文件名。当我在服务器中打印该文件名时,它打印正常,但与我硬编码的字符串不匹配。例如:我将 'Lecture.pdf' 作为文件名从客户端发送到服务器,然后我将接收到的文件名与硬编码字符串 'Lecture.pdf' 进行匹配,它不会匹配并最终 return 为假。我希望 equal 方法 return true(应该如此)。
这是一个可能会说明问题的代码片段。 'server' 是这里的 Socket 对象,我正在使用字节数组读取文件名:
InputStream is = null;
byte response [] = new byte [50];
is = server.getInputStream();
is.read(response);
String str_res = new String (response);
System.out.println ("Got reS: " + str_res);
System.out.println ( "Result: "+(response.toString()).equals ("Lecture.pdf"));
你需要写
new String(response, "UTF-8").equals ("Lecture.pdf")
或
str_res.equals("Lecture.pdf")
您将原始的、未转换的字节数组等同于字符串。字节数组永远不会等于字符串,因为它们是不同的类型。您还应该检查转换的字节数是否正确——如果您发送 1 个字节,您的输出字符串应该有多少个字符?查看 public String(byte[] bytes, int offset, int length, Charset charset) 构造函数,并跟踪您实际读取的字节数:
int bytesRead = is.read(response);
不是将 response.toString() 与硬编码值进行比较,而是比较 str_res.
response.toString()是字节数组的字符串表示。
变化:
System.out.println ( "Result: "+(response.toString()).equals ("Lecture.pdf"));
收件人:
System.out.println ( "Result: "+str_res.equals ("Lecture.pdf"));