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

[505 byte] By [charllescubaa] at [2007-11-27 8:56:09]
# 1
Ok I already know that bits are always the less significant for characters under 255, so it succeds, what about if I have Characters above 255Sorry for my english:)
charllescubaa at 2007-7-12 21:18:30 > top of Java-index,Java Essentials,Java Programming...
# 2
Cme on Guys...Easy postNo suggestion
charllescubaa at 2007-7-12 21:18:30 > top of Java-index,Java Essentials,Java Programming...
# 3
GREAT QUESTIONwhat I KNOW is: you can get a String from a byte[]I THINK this Streams may use char encoding to return chars from bytes.eg you can use the constructor String(byte[] bytes, String charsetName)
pbulgarellia at 2007-7-12 21:18:30 > top of Java-index,Java Essentials,Java Programming...
# 4
HummmInsteresting I did not know thatSo I can use diferent encodings to interpret a byte as a character?
charllescubaa at 2007-7-12 21:18:30 > top of Java-index,Java Essentials,Java Programming...
# 5
I dont know a unique byte,but a byte array certainly can be interpreted in more than one charsetAn it works fine... I had to use it one time.bye
pbulgarellia at 2007-7-12 21:18:30 > top of Java-index,Java Essentials,Java Programming...
# 6
There's FileReader and FileWriter, which are specialized to handle characters.Or you could use the String constructor with a byte array.
myncknma at 2007-7-12 21:18:30 > top of Java-index,Java Essentials,Java Programming...
# 7

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

charllescubaa at 2007-7-12 21:18:30 > top of Java-index,Java Essentials,Java Programming...
# 8

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.

myncknma at 2007-7-12 21:18:30 > top of Java-index,Java Essentials,Java Programming...