Sunteți pe pagina 1din 25

I/O, Applets and Other topics

Introduction
io and applet are 2 packages stored under java package. Io package is used for performing console based I/O, file based i/o or reading through sockets Most real world java programs are not text based but actually applet based programs relying upon javas Abstract Windows Toolkit. (AWT)

Streams
I/O is performed through streams. A stream is an abstraction which either produces or consumes information. Streams can be linked to a variety of input/output devices without bothering about the device. (Hence abstraction). All streams behave in the same manner.

Character and byte stream


Byte streams: used for handling data in bytes, useful for reading/writing binary data, at the lowest level all I/O is byte oriented. Character streams: handle input/output of characters, use Unicode and hence can be internationalized. To use stream classes we must import java.io.*;

Byte stream classes


2 abstract class hierarchy used: InputStream and OutputStream They define several abstract methods which their subclasses define. Two most used are: read() and write() which read/write bytes of data. Recognizing: End in Stream.

Character Stream classes


2 abstract class hierarchy at the top: Reader and Writer defining several abstract methods. read() and write() are most popular, which are implemented by subclasses. Recognizing: end in Reader or Writer

Predefined streams
java.lang package automatically imported in programs. This package defines a class called System, which contains three predefined stream variables in, out and err defined as public and static. Hence can be used like: System.out or System.in etc. System.out = default output stream (console) System.in = default input stream (keyboard) System.err = default error stream (console) May be redirected to any compatible input/output device

System.in is an object of type InputStream. System.out and System.err is an object of PrintStream. Both these are byte streams although both are used to read and write characters. These can be wrapped within character streams if desired.

Reading console input


We wrap System.in in a BufferedReader object to create a character stream. The constructor of BufferedReader is BuffereReader (Reader object) Reader is an abstract class, a concreate subclass of it is: InputStreamReader which converts bytes to characters. To obtain InputStreamReader object linked to System.in, use InputStreamReader(InputStream object)

Hence finally we reach this: BuffereReader br = new BufferedReader ( new InputStreamReader (System.in)); After this statement executes br is a character based stream which is linked to the keyboard using System.in. Now for reading characters we use read() method with br and for strings we use readLine() method. Prototype of read(): int read() throws IOException read() returns -1 when end of stream is encountered. Prototype for readLine(): String readLine() throws IOException.

import java.io.*; class BRRead { public static void main(String args[]) throws IOException { char c; BufferedReader br = new BufferedReader (new InputStreamReader(System.in)); System.out.println("Enter characters, 'q' to quit."); // read characters do { c = (char) br.read(); System.out.println(c); } while(c != 'q'); } }

Input sample1: 1234rtweq (Press enter now) Output: it prints 1234rtweq on new lines.

Input sample2: 1234rtwequit(Press enter now) Output: 1234rtweq (Notice how it stops at q).

import java.io.*; class BRReadLines { public static void main(String args[]) throws IOException { // create a BufferedReader using System.in BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str; System.out.println("Enter lines of text."); System.out.println("Enter 'stop' to quit."); do { str = br.readLine(); System.out.println(str); } while(!str.equals("stop")); } }

Enter lines of text. Enter 'stop' to quit. My name is Gaurav Saxena stop Hanuman (Press Enter) My name is Gaurav Saxena stop Hanuman stop (Press Enter) stop

class TinyEdit { public static void main(String args[]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str[] = new String[100]; System.out.println("Enter lines of text."); System.out.println("Enter 'stop' to quit."); for(int i=0; i<100; i++) { str[i] = br.readLine(); if(str[i].equals("stop")) break; } System.out.println("\nHere is your file:");

// display the lines for(int i=0; i<100; i++) { if(str[i].equals("stop")) break; System.out.println(str[i]); } } }

Writing console Output


Accomplished using print() and println() method (defined by PrintStream class) PrintStream is derived from OutputStream it implements low level method write(). Prototype for write is: void write (int val) Although val is declared as an integer only the lower 8 bits are written.

class WriteDemo { public static void main(String args[]) { int b; b = 'A'; System.out.write(b); System.out.write('\n'); } } //output prints A then a newline //Value stored in b is 65 //Strangely does not work without \n

PrintWriter class
Character based class recommended for real life java programs. Defines several constructors one of which: PrintWriter( OutputStream object, boolean flushOnNewLine); Boolean variable above controls whether automatic flushing takes place automatically or not when println() is called. Supports print() and println() method. If an argument is not of simple type, it calls the objects toString() method.

import java.io.*; public class PrintWriterDemo { public static void main(String args[]) { PrintWriter pw = new PrintWriter(System.out, true); pw.println("This is a string"); int i = -7; pw.println(i); double d = 4.5e-7; pw.println(d); } }

Reading and Writing Files


All file I/O is byte oriented, but streams can be wrapped in character streams. To read we use FileInputStream and to write we use FileOutputStream. Constructors: FileInputStream ( String Filename) throws FileNotFoundException FileOutputStream ( String Filename) throws FileNotFoundException

Exception thrown when no file exists (for reading) or File cannot be created (for writing) If existing file opened for writing, all contents destroyed (or we say any file by the same name is destroyed). File is closed using close() method with syntax: void close() throws IOException To read we use read() which picks 1 byte from file and returns it as an integer value and returns -1 at EOF.

import java.io.*; class ShowFile { public static void main(String args[]) throws IOException { int i; FileInputStream fin; try { fin = new FileInputStream(args[0]); } catch(FileNotFoundException e) { System.out.println("File Not Found"); return; } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Usage: ShowFile File"); return; } // read characters until EOF is encountered do { i = fin.read(); if(i != -1) System.out.print((char) i); } while(i != -1); fin.close(); } }

class CopyFile { public static void main(String args[]) throws IOException { int i; FileInputStream fin; FileOutputStream fout; try { try { fin = new FileInputStream(args[0]); } catch(FileNotFoundException e) { System.out.println("Input File Not Found"); return; } try { fout = new FileOutputStream(args[1]); } catch(FileNotFoundException e) { System.out.println("Error Opening Output File"); return; } } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Usage: CopyFile From To"); return; }

try { do { i = fin.read(); if(i != -1) fout.write(i); } while(i != -1); } catch(IOException e) { System.out.println("File Error"); }
fin.close(); fout.close(); }

S-ar putea să vă placă și