1

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

2 Answers 2

3

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);
Sign up to request clarification or add additional context in comments.

3 Comments

That didn't work either. Shouldn't response.toString () be enough to convert byte array to string?
Print the string out, and print the length of the string out to see what's going on. You're probably using the wrong number of bytes. I've updated the answer. Good luck!
You are right! That was the problem . Thank you very much :)
0

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

2 Comments

That didn't fix it. Btw I want to the file name and start reading that file and that isn't working for me because the file name after after conversion to string wont match the actual file names in my system (although Lecture.pdf exists in the same directory as my code)
You said that str_res printed out fine? Does that mean is prints out "Lecture.pdf"? Are there any extra spaces?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.