Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

FileReader question 1

Status
Not open for further replies.

tikual

Technical User
Jun 10, 2003
237
HK
Hi all,

Suppose a file contains "abcd", why FileReader can read the char in 'a', 'b', 'c', 'd' but not 'ab' and 'cd'? Why not it reads 16 bits a times?

Thanks,

tikual
 
There's a read method on the FileReader class which can read multiple characters into an array.

Tim
 
Hi Tim,

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?

Thanks!

tikual
 
FileReader is intended for files containing textual information, whereas FileInputStream deals with Files as a collection of bytes.

Tim
 
Hi Tim,

Let's see my simple code:

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);
}

reader.close();
writer.close();
}
}

tikual
 
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.

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
Hi sedj,

Thanks for your help!!!

tikual
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top