FileInputStream is used to read, it is practically the same as with FileReader , using the read () method, when it reaches the end of the file it returns -one. Its basic difference is that with FileReader we read characters and FileInputStream reads bytes . For example:
import java.io.*;
public class FicherosBinariosApp {
public static void main(String[] args) {
try(FileInputStream fis=new FileInputStream("D:\fichero_bin.ddr")){
int valor=fis.read();
while(valor!=-1){
System.out.print((char)valor);
valor=fis.read();
}
}catch(IOException e){
}
}
}
For java, a class Reader is a class that reads characters. This is more like what we want. A Reader has methods to read characters. With this class we could already work. Sorry, we still have System.in , which is a InputStream and not a Reader .
How do we convert the System.in to Reader ?. There is a class in java, the InputStreamReader , which makes this conversion. To get a Reader , we just need to instantiate a InputStreamReader by passing a InputStream in the constructor. The code is as follows
InputStreamReader isr = new InputStreamReader(System.in);
We are declaring a variable "isr" of type InputStreamReader . We create an object of this class by doing new InputStreamReader (...) . In parentheses we passed the InputStream that we want to convert to Reader , in this case, the System.in
We already have the Reader . How does it work exactly?
InputStreamReader is a Reader . It behaves the same as in Reader and can be put anywhere that supports a Reader . That is, we can read characters from it.
When building it we have passed a InputStream , specifically, System.in. InputStreamReader somehow it is stored inside.
When we ask for InputStreamReader characters, it asks the InputStream which has the bytes saved, converts them to characters and returns them to us.
The mechanism to obtain a BufferedReader from another Reader , anyone (for example the InputStreamReader ), is similar to the one we used before. We instantiate it by passing it on the Reader . The code is:
BufferedReader br = new BufferedReader (isr);
The operation of this class is the same as the InputStreamReader . When we ask for a complete line of characters (a String ), she asks the Reader that she has inside, converts them to String and returns it to us.
To request a String , the readLine () method is used. This method reads all typed characters (received if it was another input device) until you find the key press , or whatever you want to call it.
String texto = br.readLine();
This reads a full String from the keyboard and stores it in a "text" variable.