Reputation: 331
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?
Upvotes: 3
Views: 1867
Reputation: 6390
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 doesinputStream.read()
read the filec:/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 thatFileInputStream#read
is used to read the byte of data from the input stream.
So , FileInputStream
reads data byte
by byte
.
Upvotes: 4