Reputation: 4703
I want to put a double array into DataInputStream and print it with DataOutputStream in console. I tried to convert it to byte array first. I can't flush() DataOutputStream, so it gets printed in console. System.out.print(c) works.
double[] b = { 7, 8, 9, 10 };
//double[] to byte[]
byte[] bytes = new byte[b.length * Double.SIZE];
ByteBuffer buf = ByteBuffer.wrap(bytes);
for (double d : b)
buf.putDouble(d);
InputStream is = new ByteArrayInputStream(bytes);
DataInputStream dis = new DataInputStream(is);
DataOutputStream dos = new DataOutputStream(System.out);
int c;
try{
while( (c = dis.read()) != -1){
//System.out.print(c);
dos.writeInt(c);
}
dos.flush();
}
catch(Exception e){
System.out.println("error: " + e);
}
Output with System.out.print(c), what I want to achieve: 642800000064320000006434000000643600000000000000000000000000000000[...]
Upvotes: 1
Views: 350
Reputation: 20803
Writing bytes to console may cause control characters( that can not be printed) and would cause unexpected result. If you absolutely need to see the text representation, you would consider ASCII converters such as Base64.
But in your example, replace
dos.writeInt(c);
with dos.writeChars(Integer.toString(n));
and you will get expected result. writeInt
writes 4 bytes representing current int and that can result in various control characters. writeChars
writes a sequence of characters instead.
Upvotes: 1