permaculture playing cards*
The moose likes Java in General and the fly likes why is int required as FileOutputStream's argument? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Java in General
Bookmark "why is int required as FileOutputStream Watch "why is int required as FileOutputStream New topic
Author

why is int required as FileOutputStream's argument?

Sriram Sharma
Ranch Hand

Joined: Apr 12, 2006
Posts: 98
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: 18570
    
    8

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: 98
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: 19697
    
  20

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 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Sriram Sharma
Ranch Hand

Joined: Apr 12, 2006
Posts: 98
Thanks a lot Rob. That was pretty good explanation
-Ram
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: why is int required as FileOutputStream's argument?