| Author |
why is int required as FileOutputStream's argument?
|
Sriram Sharma
Ranch Hand
Joined: Apr 12, 2006
Posts: 89
|
|
Dear All,
I was trying some very basic stuffs using input and output streams.
Here below is the snippet...
The above stated code snippet works fine if executed as such. But......
If I give "fos.write(fis.read())" instead of "fos.write(c)", the output file contains only some junk characters.
Can somebody explain me why this is so???
Regards,
Ram
|
 |
Paul Clapham
Bartender
Joined: Oct 14, 2005
Posts: 16483
|
|
|
Well, for one thing you would only be writing every other byte from the input to the output, instead of every byte.
|
 |
Sriram Sharma
Ranch Hand
Joined: Apr 12, 2006
Posts: 89
|
|
Hi Paul/other ranchers,
Thanks for replying...
But still, I did not get what you wanted to communicate.
Could you please elaborate it for me?
Regards,
Ram
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
InputStream.read() reads one character, moves forward and then returns the read character. So if you call read() twice in the loop, once in the guard and once in the writing, then the first, third, fifth etc bytes are not written. Also, if there is an odd number of bytes then the guard will return something other than -1, but the read used in the write returns -1 and this is then written as a byte.
You could try without reading in the guard but you wouldn't know when to stop:
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Sriram Sharma
Ranch Hand
Joined: Apr 12, 2006
Posts: 89
|
|
Thanks a lot Rob. That was pretty good explanation
-Ram
|
 |
 |
|
|
subject: why is int required as FileOutputStream's argument?
|
|
|