Different bytes read from which I wrote - java

I'm trying to write a byte array to file and then to read it again. The problem is that the byte array that I Read is different from that I wrote.
The output of the code below is:
[B#21a06946 (Original byte array written)
[B#2fc14f68 (byte array read )
byte[] encryptedKey = rsaCipher.encrypt(AESKey, publicKeyPathName, transformation, encoding);
System.out.println(encryptedKey);
List<byte[]> list = new ArrayList<byte[]>();
list.add(encryptedKey);
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("encryptedKey"));
out.writeObject(list);
out.close();
ObjectInputStream in = new ObjectInputStream(new FileInputStream("encryptedKey"));
List<byte[]> byteList = (List<byte[]>) in.readObject();
in.close();
byte[] encryptedKey2 = byteList.get(0);
System.out.println(encryptedKey2);

Arrays do not have a proper String representation. To see the content, use the below instead
System.out.println(java.util.Arrays.toString(encryptedKey));
System.out.println(java.util.Arrays.toString(encryptedKey2));

Related

reading bytearray upto specified location

Let me allow to describe my problem:
I have created socket server in python and client in java, from java I am sending multiple objects to server by using :
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ByteArrayOutputStream append = new ByteArrayOutputStream();
ObjectOutput out = null;
byte finalarr[]=null;
try {
out = new ObjectOutputStream(bos);
out.writeObject(object);
out.flush();
byte[] objByte = bos.toByteArray();
bos.close();
out.close();
append.write(objByte.length);
append.write(objByte);
bos = new ByteArrayOutputStream();
out = new ObjectOutputStream(bos);
out.writeObject(value);
out.flush();
append.write(bos.toByteArray());
finalarr = append.toByteArray( );
os = sChannel.socket().getOutputStream();
oos = new ObjectOutputStream(os);
oos.write(finalarr);
} finally {
try {
bos.close();
} catch (IOException ex) {
}
}
Now, finalarr contains byte length of object then actual byte[] of object and then byte[] of value. Now in python after receiving this First I want to read length of byte which is written in first position of finalarr then whatever length I get I want to read received array upto that length so that I will get object separately then the remaining part separately.
In python I have done upto this:
total_data=b''
while True:
data = self.clientsocket.recv(1024)
if not data: break
total_data += data
In total_data I am getting entire bytearray, but I don't know how I can read it so that I can get two objects separately as explained.

Convert Contents Of A ByteArrayInputStream To String

I read this post but I am not following. I have seen this but have not seen a proper example of converting a ByteArrayInputStream to String using a ByteArrayOutputStream.
To retrieve the contents of a ByteArrayInputStream as a String, is using a ByteArrayOutputstream recommended or is there a more preferable way?
I was considering this example and extend ByteArrayInputStream and utilize a Decorator to increase functionality at run time. Any interest in this being a better solution to employing a ByteArrayOutputStream?
A ByteArrayOutputStream can read from any InputStream and at the end yield a byte[].
However with a ByteArrayInputStream it is simpler:
int n = in.available();
byte[] bytes = new byte[n];
in.read(bytes, 0, n);
String s = new String(bytes, StandardCharsets.UTF_8); // Or any encoding.
For a ByteArrayInputStream available() yields the total number of bytes.
Addendum 2021-11-16
Since java 9 you can use the shorter readAllBytes.
byte[] bytes = in.readAllBytes();
Answer to comment: using ByteArrayOutputStream
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[8192];
for (;;) {
int nread = in.read(buf, 0, buf.length);
if (nread <= 0) {
break;
}
baos.write(buf, 0, nread);
}
in.close();
baos.close();
byte[] bytes = baos.toByteArray();
Here in may be any InputStream.
Since java 10 there also is a ByteArrayOutputStream#toString(Charset).
String s = baos.toString(StandardCharsets.UTF_8);
Why nobody mentioned org.apache.commons.io.IOUtils?
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.IOUtils;
String result = IOUtils.toString(in, StandardCharsets.UTF_8);
Just one line of code.
Java 9+ solution:
new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
Use Scanner and pass to it's constructor the ByteArrayInputStream then read the data from your Scanner , check this example :
ByteArrayInputStream arrayInputStream = new ByteArrayInputStream(new byte[] { 65, 80 });
Scanner scanner = new Scanner(arrayInputStream);
scanner.useDelimiter("\\Z");//To read all scanner content in one String
String data = "";
if (scanner.hasNext())
data = scanner.next();
System.out.println(data);
Use Base64 encoding
Assuming you got your ByteArrayOutputStream :
ByteArrayOutputStream baos =...
String s = new String(Base64.Encoder.encode(baos.toByteArray()));
See http://docs.oracle.com/javase/8/docs/api/java/util/Base64.Encoder.html

How to convert byte array to long without using java.nio?

I am implementing a reliable data transfer protocol. I need to pass the checksum which is long value to a receiver. I am not allowed to use java.nio.
I know how to convert long to byte array as show below:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
dos.writeLong(someLong);
dos.close();
byte[] longBytes = baos.toByteArray();
But how do I convert byte array to long without using java.nio?
You can do like this
ByteArrayInputStream bais = new ByteArrayInputStream(longBytes);
DataInputStream dis = new DataInputStream(bais);
someLong = dis.readLong();

Receive byte[] using ByteArrayInputStream from a socket

Here is the code but got error:
bin = new ByteArrayInputStream(socket.getInputStream());
Is it possible to receive byte[] using ByteArrayInputStream from a socket?
No. You use ByteArrayInputStream when you have an array of bytes, and you want to read from the array as if it were a file. If you just want to read arrays of bytes from the socket, do this:
InputStream stream = socket.getInputStream();
byte[] data = new byte[100];
int count = stream.read(data);
The variable count will contain the number of bytes actually read, and the data will of course be in the array data.
You can't get an instance of ByteArrayInputStream by reading directly from socket.
You require to read first and find byte content.
Then use it to create an instance of ByteArrayInputStream.
InputStream inputStream = socket.getInputStream();
// read from the stream
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] content = new byte[ 2048 ];
int bytesRead = -1;
while( ( bytesRead = inputStream.read( content ) ) != -1 ) {
baos.write( content, 0, bytesRead );
} // while
Now, as you have baos in hand, I don't think you still need a bais instance.
But, to make it complete,
you can generate byte array input stream as below
ByteArrayInputStream bais = new ByteArrayInputStream( baos.toByteArray() );

byte array in java returning null after conversion from objects

I need to send my phone contacts in android as bytes. So i have crated a bean class implementing serializable , but after converting the arraylist of bean class to byte array, byte array is always showing null. Here is my sample code.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(presentContacts);
byte[] buf = baos.toByteArray();
Here presentContacts is the ArrayList of bean class. Byte array, buf is always returning null but presentContacts is not null.
You should probably close or at least flush the ObjectOutputStream.
Something like this
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(presentContacts);
oos.flush();
byte[] buf = baos.toByteArray();

Categories