简体   繁体   中英

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM