Input Streams.read() How does it work exactly?

Fabian Andiel :

I'm having the following code :

public static void main(String[] args) throws Exception {

 FileInputStream inputStream = new FileInputStream("c:/data.txt");

 FileOutputStream outputStream = new FileOutputStream("c:/result.txt");

 while (inputStream.available() > 0) {
  int data = inputStream.read(); 
  outputStream.write(data); 
 }

 inputStream.close(); 
 outputStream.close();
}

I dont get my head around the following line: int data = inputStream.read();

Get the bytes of the file c:/data.txt, read byte by byte, and then get concatenated automatically within the variable data or does inputStream.read() read the file c:/data.txt all at once and assign everything to the data variable?

Vishwa Ratna :

From JavaDoc:

A FileInputStream obtains input bytes from a file in a file system. FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader

Question: Get the bytes of the file c:/data.txt, read byte by byte, and then get concatenated automatically within the variable data or does inputStream.read() read the file c:/data.txt all at once and assign everything to the data variable?

To Answer this lets take example:

try {
  FileInputStream fin = new FileInputStream("c:/data.txt");
  int i = fin.read();
  System.out.print((char) i);
  fin.close();
} catch (Exception e) {
  System.out.println(e);
}

Before running the above program a data.txt file was created with text: Welcome to Stackoverflow.

After the execution of above program the console prints single character from the file which is 87 (in byte form), clearly indicating that FileInputStream#read is used to read the byte of data from the input stream.


So , FileInputStream reads data byte by byte.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=414975&siteId=1