file - How FileInputStream and FileOutputStream Works in Java? -


i'm reading input/output streams in java on java tutorials docs. tutorials writer use example:

import java.io.fileinputstream; import java.io.fileoutputstream; import java.io.ioexception;  public class copybytes {     public static void main(string[] args) throws ioexception {          fileinputstream in = null;         fileoutputstream out = null;          try {             in = new fileinputstream("xanadu.txt");             out = new fileoutputstream("outagain.txt");             int c;              while ((c = in.read()) != -1) {                 out.write(c);             }         } {             if (in != null) {                 in.close();             }             if (out != null) {                 out.close();             }         }     } } 

xanadu.txt file data:

in xanadu did kubla khan stately pleasure-dome decree: alph, sacred river, ran through caverns measureless man down sunless sea. 

output outagain.txt file:

in xanadu did kubla khan stately pleasure-dome decree: alph, sacred river, ran through caverns measureless man down sunless sea. 
  1. why writers use int c if reading characters?

  2. why use -1 in while condition?

  3. how out.write(c); method convert int again characters?

1: want ask why writer use int c? reading characters.

fileinputstream.read() returns 1 byte of data int. works because byte can represented int without loss of precision. see this answer understand why int returned instead of byte.

2: second why use -1 in while condition?

when end of file reached, -1 returned.

3: how out.write(c); method convert int again characters? provide same output in outagain.txt file

fileoutputstream.write() takes byte parameter int. since int spans on more values byte, 24 high-order bits of given int ignored, making byte-compatible value: int in java always 32 bits. removing 24 high-order bits, you're down 8 bits value, i.e. byte.

i suggest read javadocs each of method. reference, answer of questions:

read:

reads next byte of data input stream. value byte returned int in range 0 255. if no byte available because end of stream has been reached, value -1 returned. method blocks until input data available, end of stream detected, or exception thrown.

write:

writes specified byte output stream. general contract write 1 byte written output stream. byte written 8 low-order bits of argument b. 24 high-order bits of b ignored.


Comments