简体   繁体   中英

Can't flush DataOutputStream in Java

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[...]

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.

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