Problem : How you can read from a Keyboard and write to a text file, just like DOS copycon command?
Solution : Keyboard is represented by an object System.in. System.in.read() method returns bytes for charters those are entered from keyboard. We need a filter class java.io.InputStreamReader to convert bytes into characters. But we want to read data line by line so charters are converted into lines with help of java.io.BufferedReader class. Lines then will be written to a file with help of java.io.PrintWriter class. PrintWriter in turn connected with FileWrite to write charcetrs on a file. Is that clear ?? Lets start a sample program. Program :Step 1 - CodingCreate a text file c:/sunilos/Copycon.java and copy below contents.import java.io.BufferedReader; import java.io.FileWriter; import java.io.InputStreamReader; import java.io.PrintWriter; /** * A program to read data from keyboard and write to file until 'quit' sting is entered. * */ public class Copycon { public static void main(String[] args) throws Exception { String target ="c:/sunilos/sunilos-keyboard.txt"; FileWriter writer = new FileWriter(target); PrintWriter printWriter = new PrintWriter(writer); InputStreamReader inputStreamReader = new InputStreamReader(System.in); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String line = bufferedReader.readLine(); while(!line.equals("quit")){ printWriter.print(line); line = bufferedReader.readLine(); } printWriter.close(); inputStreamReader.close(); } } Step 2 - Deployment
Step 3 - Testing
OutputC:\sunilos> >Hi >How R U ? >I Pretty Good, I am in hurry >Bye >quit FAQWhat is InputStreamReader?
Most Interesting methods in InputStreamReader?
<<Previous | Next>> |