A_Javed
A_Javed

Reputation: 48

string.equal method not working

I'm new to java. The problem that I'm right now is that I'm sending a file name from the client to the server. When I print that file name in server, it prints fine but it wont match the string that I've hard-coded. Eg: I'm sending 'Lecture.pdf' as a file name from client to server and then I match the received file name with hard coded string 'Lecture.pdf', it wont match and eventually return false. I expect the equal method to return true (as it should).

Here is a code snippet that might demonstrate the problem. 'server' is the object of Socket here, and I'm reading file name using byte array:

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"));

Upvotes: 1

Views: 222

Answers (2)

mk.
mk.

Reputation: 11710

You need to write

new String(response, "UTF-8").equals ("Lecture.pdf")

or

str_res.equals("Lecture.pdf")

You're equating your original, unconverted byte array to a string. A byte array will never be equal to a string, because they are different types. You should also check that the correct number of bytes is being converted - if you send 1 byte, how many characters should your output string have? Check out the public String(byte[] bytes, int offset, int length, Charset charset) constructor, and keep track of how many bytes you actually read using:

int bytesRead = is.read(response);

Upvotes: 3

barbiepylon
barbiepylon

Reputation: 911

Instead of comparing response.toString() to the hard-coded value, compare str_res.

response.toString() is the string representation of the byte array.

Change:

System.out.println ( "Result: "+(response.toString()).equals ("Lecture.pdf")); 

To:

System.out.println ( "Result: "+str_res.equals ("Lecture.pdf"));

Upvotes: 0

Related Questions