S. A. Malik
S. A. Malik

Reputation: 3655

Java PrintWriter Not sending Byte Array

A byte array of unknown size is needed to be sent over a socket. When i try to write the byte array to printwriter like

        writeServer = new PrintWriter(socketconnection.getOutputStream());
        writeServer.flush();
        writeServer.println("Hello World");
        writeServer.println(byteArray.toString());

It is received at the server but is only a string of 5-6 characters always starting from [B@..... But when i send it through the output stream like

        writeServer.println("Hello World");
        socketconnection.getOutputStream().write(byteArray);

It is received at the server correctly. But the issue is in the second option the "Hello World" String does not go through to the server. I want both of things delivered to the server.

How should i do it?

Upvotes: 1

Views: 7391

Answers (2)

Amit Deshpande
Amit Deshpande

Reputation: 19185

byteArray.toString() will return you human readable form of byteArray. Even though for Arrays it is never human readable.

If you want to transfer byteArray as String then you should use

String str = new String(bytes, Charset.defaultCharset());//Specify different charset value if required.

Upvotes: 2

Peter Lawrey
Peter Lawrey

Reputation: 533442

You are trying to mix binary and text which is bound to be confusing. I suggest you use one or the other.

// as text
PrintWriter pw = new PrintWriter(socketconnection.getOutputStream());
pw.println("Hello World");
pw.println(new String(byteArray, charSet);
pw.flush();

or

// as binary
BufferedOutputStream out = socketconnection.getOutputStream();
out.write("Hello World\n".getBytes(charSet));
out.write(byteArray);
out.write(`\n`);
out.flush();

Upvotes: 2

Related Questions