90 likes | 282 Views
2.0 FUNDAMENTALS OF JAVA PROGRAMMING LANGUAGE. 2.4 Apply Input and Output Streams. FP301 OBJECT ORIENTED PROGRAMMING. Learning Outcome Subtopic 2.4. FP301 OBJECT ORIENTED PROGRAMMING. INPUT & OUTPUT STREAM.
E N D
2.0 FUNDAMENTALS OF JAVA PROGRAMMING LANGUAGE 2.4 Apply Input and Output Streams
FP301 OBJECT ORIENTED PROGRAMMING Learning Outcome Subtopic 2.4
FP301 OBJECT ORIENTED PROGRAMMING INPUT & OUTPUT STREAM • Input stream refers to the flow of data to a program from an input device (System.in). • Output stream refers to the flow of data from a program to an output device (System.out).
FP301 OBJECT ORIENTED PROGRAMMING INPUT & OUTPUT STREAM • 1. To display output used : • System.out.print • or • System.out.println • 2. To read input data from user used : • System.in
FP301 OBJECT ORIENTED PROGRAMMING InputStreamReader & OutputStreamReader • An InputStreamReader is a bridge from byte streams to character streams • It reads bytes and decodes them into characters using a specified charset. • The charset that it uses may be specified by name or may be given explicitly, or the platform's default charset may be accepted.
InputStreamReader Class • Offers backward compatibility with older input streams Example: System.in • Constructors InputStreamReader(InputStream input) – connects an input stream to the reader InputStreamReader(InputStream input, String encoding) – connects an input stream to the reader using the specified encoding form • Methods String getEncoding( ) – returns the name of the character encoding used by the
The Use of InputStreamReader & BufferedReader Example 1 import java.io.*; //This is a package to be used while using input and output statements in a program class Act2G { public static void main (String args[]) throws IOException { BufferedReaderstdin = new BufferedReader (new InputStreamReader(System.in)); //This is to enable input from keyboard String str; System.out.println("Enter the data : "); str = stdin.readLine(); //Text data is received from the standard input device, keyboard System.out.println("You have entered: " + str); } }
Cont.. Example 2 import java.io.*; public class InputStreamToReaderDemo { public static void main(String args[]) { try { System.out.print ("Please enter your name : "); // Get the input stream representing standard input InputStream input = System.in; // Create an InputStreamReader InputStreamReader reader = new InputStreamReader ( input ); // Connect to a buffered reader, to use the readLine() method BufferedReaderbufReader = new BufferedReader ( reader ); String name = bufReader.readLine(); System.out.println ("Pleased to meet you, " + name); } catch (IOExceptionioe) { System.err.println ("I/O error : " + ioe); } } }