I confused in the difference between the read method of FileReader and FileInputStream. How many bit it reads a times? Not 16 bit and 8 bit? If I output the file from these two streams, both return the same content of "abcd" file. So what is the difference?
The content of "source.txt" is "abcd". How to explan that the System.out.println shows the same value in these two loops? I understand the purpose of these two classes. But, it returns the same value per each cycle. I would like to know how many bits it reads of FileReader and FileInputStream respectively.
import java.io.*;
public class TwoStreamWriter{
public static void main(String[] args)throws IOException{
File input = new File("source.txt");
InputStream in = new FileInputStream(input);
OutputStream out = new FileOutputStream("output1.txt");
int byteRead;
while ( (byteRead = in.read()) != -1 ){
System.out.println(byteRead);
out.write(byteRead);
}
in.close();
out.close();
Reader reader = new FileReader(input);
Writer writer = new FileWriter("output2.txt");
int charRead;
while ( (charRead = reader.read()) != -1 ){
System.out.println(charRead);
writer.write(charRead);
}
According to the API, FileInputStream.read() reads a byte (8 bits), and a FileReader.read() reads a character (16 bits).
I **think** this can be explained by the following ...
Now, the int values of 'a' 'b' 'c' and 'd' are, respectively 97 98 99 100 . These ints fit into a byte structure - because, while an int can be 32 bits, a small number, like those above, will not fill all those bits.
Hence, when the filereader reads the char, not all the 16 bits are used - so you see the same output.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.