Engineering Full Stack Apps with Java and JavaScript
Need to read data from Keyboard in a machine independent way.
DataInputStream is a FilterInputStream that read primitive data from an underlying input stream in a machine-independent way.
It provides convenience methods such as readInt(), readChar etc.
Below program will take the input from keyboard using DataInputStream with its inherited read method and print it to a file using FileOutputStream.
import java.io.*;
public class FileCopier {
public static void main(String[] args) throws IOException {
DataInputStream dis = new DataInputStream(System.in);
FileOutputStream fout = new FileOutputStream("myFile.txt");
System.out.println("Enter text (enter & to end):");
char ch;
while ((ch = (char) dis.read()) != '&')
fout.write(ch);
fout.close();
}
}
Input will be read byte by byte and ends reading when a '&' is encountered.
FileOutputStream constructor takes the name of the file as an argument.
System.in is of type PrintStream and represents the standard input device which is keyboard by default.
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.