I came across the below statement in this tutorial.
while an InputStream returns one byte at a time, meaning a value between 0 and 255 (or -1 if the stream has no more data), the Reader returns a char at a time, meaning a value between 0 and 65535 (or -1 if the stream has no more data).
Below is the example code -
Reader reader = new FileReader("c:\\data\\myfile.txt");
int data = reader.read();
while(data != -1){
char dataChar = (char) data;
data = reader.read();
}
The code for InputStream is similar as well. Instead of FileReader & Reader ;FileInputStream and InputStream are used. Reader returns char while InputStream stream returns a byte. In both cases when I test using Strings such as "Hello World" , it reads one character at a time. What are the values that is beyond 255 which I can use to see the difference between these byte based and char based input.
Working Program
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
public class ReaderStream {
public static void main(String[] args) {
String data = "படிகஅமைப்பு";
InputStream input = new ByteArrayInputStream(data.getBytes());
Reader inputStream = new InputStreamReader(input);
try {
int readData = inputStream.read();
while(readData != -1) {
System.out.print((char)readData);
readData = inputStream.read();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("");
input = new ByteArrayInputStream(data.getBytes());
try {
int readData = input.read();
while(readData != -1) {
System.out.print((char)readData);
readData = input.read();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Output
படிகஅமைப்பு
பà®à®¿à®à®à®®à¯à®ªà¯à®ªà¯