Byte and Character Streams
Hi
I have an insane doubt, wish U can help me
Java has two classes (FileInputStream and FileOutputStream) which allow u to read one single byte from a stream or to write One single byte out to a stream.
A classic example provided by Sun has a loop which reads one byte at a time and writes it out until there is no byte left.
What I dont get is: if char in Java is Sixteen bits (2 bytes) how can such streams read characters if they read one single byte?
Tnx in advnce
Yeahh
I have tested these streams. What I dont get is: how can FileInputStream which reads one byte at a time read characters properly?
Strange!!!
Well. FileInputStream can read characters under 255. In java char type is 2 bytes length, what characters can we store in a char var.?
import java.io.FileReader;
char[] read(FileInputStream in, int limit) {
FileReader reader = new FileReader(in);
char[] array = new char[limit];
for (int i = 0; i < limit; i++) {
int value = reader.read();
if (value == -1) break;
array[i] = (char)value;
}
return array;
}
This code is not ideal, but it should give you an idea of how to get an character from an input stream.