If I want to read ahead a byte,and push it back if it is not '<',I can do it like this:
PushbackInputStream pbin=new PushbackInputStream(new FileInputStream("1.dat"));
int b = pbin.read();
if(b!='<')
pbin.unread(b);
But if I want to push back a double that I read from DataInputStream,what shall i do? For example:
PushbackInputStream pbin1=null;
DataInputStream din=new DataInputStream(
pbin1=new PushbackInputStream(
new FileInputStream("1.dat")
)
);
double d = din.readDouble();
pbin1.unread(d);
The last line pbin1.unread(d);
can not be compiled,because the PushbackInputStream can not push back a double,how can I convent the double to byte array?or any other way?
You can't push back a double that way. Method DataInputStream.readDouble()
reads 8 bytes to create a double, you can't just pass a double to PushbackInputStream.unread()
and expect him to know how to deal with.
To achieve what you want the solution is simple:
PushbackInputStream pbin1=new PushbackInputStream(new FileInputStream("1.dat"));
DataInputStream din=new DataInputStream(pbin1);
double d = din.readDouble(); // Get the double out of the stream
byte[] doubleAsBytes = new byte[8];
ByteBuffer.wrap(doubleAsBytes).putDouble(d); // transform the double into his byte representation
pbin1.unread(doubleAsBytes); // push back the bytes