Reading Data From Keyboard Using DataInputStream BufferedReader and Scanner
Reading Data From Keyboard Using DataInputStream BufferedReader and Scanner
Below program will take the input from keyboard using DataInputStream with its inherited read method
and print it to a file using FileOutputStream.
Code
import java.io.*;
char ch;
fout.write(ch);
fout.close();
Input will be read on every new line byte by byte and ends reading when a '&' is encountered.
FileOutputStream is a low level byte stream, whose constructor takes the name of the file as an
argument. If you are not clear about streams, please do read ‘introduction to streams’ first. Here the
DataInputStream wraps the System.in variable. System class’s static member variable ‘in’ (System.in) is
of type PrintStream and represents the standard input device that is keyboard by default.
To use the methods implemented for the DataInput interface, you need to understand the contract of
DataInput well or you might run into errors or confusion. Also, the readLine() method of the
DataInputStream is deprecated as method does not properly convert bytes to characters. To use
readLine() and other character convenience methods, a more popular approach is to use a
BufferedReader with InputStreamReader.
Code
import java.io.*;
while (!str.equals("end")) {
str = br.readLine();
fout.write(str.getBytes());
fout.write(System.lineSeparator().getBytes());
fout.close();
br.close();
}
I have only replaced DataInputStream with BufferedReader from the previous example, and kept the
FileOutputStream for writing to file, as is. FileOutputStream operate with bytes, but readLine() of
BufferedReader returns a String. Hence you need to convert your String to bytes using String's getBytes
method. You can use a FileWriter or a BufferedWriter to write strings to the file without any casting or
explicit conversion.
Code
import java.io.*;
while (!str.equals("end")) {
str = br.readLine();
fw.write(str);
fw.write(System.lineSeparator());
fw.close();
br.close();
Note that you no longer has to use getBytes() method of the String. Using a BufferedWriter will still
improve the code in terms of performance and also adds a convenience method newLine() which will
print the line separator string as defined by the system property line.separator. You can attach a
FileWriter to a BufferedWriter as:
BufferedWriter bw = new BufferedWriter(fw);
fw.write(System.lineSeparator());
with
bw.newLine();
For reading data from keyboard, we can attach the PrintStream System.in which reprecents the default
input device (which is usually keyboard).
Code
import java.io.*;
import java.util.Scanner;
while (!str.equals("end")) {
str = sc.nextLine();
fw.write(str + "\n");
}
fw.close();
sc.close();
Scanner can do lot more than these and we will see them in a separate note.
Source : http://javajee.com/reading-data-from-keyboard-using-datainputstream-bufferedreader-and-scanner