6 IO Streams

download 6 IO Streams

of 29

description

java io streams

Transcript of 6 IO Streams

  • USING I/O

  • Java I/OJava does provide strong, flexible support for I/O as it relates to files and networks.Javas I/O system is cohesive and consistent.Java programs perform I/O through streams.A stream is an abstraction that either produces or consumes information. Input stream can abstract many different kinds of input: from a disk file, a keyboard, or a network socket. Output stream may refer to the console, a disk file, or a network connection.Java implements streams within class hierarchies defined in the java.io package.

    *

  • Types of StreamsJava 2 defines two types of streamsByte StreamsCharacter Streams*

  • Byte StreamsByte streams provide a convenient means for handling input and output of bytes.Byte streams are defined by using two class hierarchies.At the top are two abstract classes: InputStream and OutputStream.The abstract classes InputStream and OutputStream define several key methods that the other stream classes implement.Two of the most important are read( ) and write( ).*

  • Byte Stream Classes*

  • Character Streams Character streams provide a convenient means for handling input and output of characters.Character streams are defined by using two class hierarchies.At the top are two abstract classes, Reader and Writer.The abstract classes Reader and Writer define several key methods that the other stream classes implement. Two of the most important methods are read( ) and write( ).

    *

  • Character Stream Classes*

  • The Predefined StreamsSystem ClassStream Variables in, out, errSystem.out refers to the standard output stream.System.in refers to standard input stream.System.err refers to the standard error stream.System.in is an object of type InputStream; System.out and System.err are objects of type PrintStream.*

  • Reading Console InputInputStream defines only one input method, read( ), which reads bytes.// Read an array of bytes from the keyboard.import java.io.*;class ReadBytes { public static void main(String args[])throws IOException{byte data[] = new byte[10];System.out.println("Enter some characters.");System.in.read(data);System.out.print("You entered: ");for(int i=0; i < data.length; i++)System.out.print((char) data[i]);}}*

  • Writing Console OutputPrintStream is an output stream derived from OutputStream, it also implements the low-level method write( ).// Demonstrate System.out.write().class WriteDemo {public static void main(String args[]) {int b;b = 'X';System.out.write(b);System.out.write('\n');}}*

  • Console Input Using Character StreamsThe best class for reading console input is BufferedReader, which supports a buffered input stream.Use InputStreamReader, which converts bytes to characters.To obtain an InputStreamReader object, use the constructor shown here:InputStreamReader(InputStream inputStream)Since System.in refers to an object of type InputStream, it can be used for inputStream.To construct a BufferedReader use the constructor shown here:BufferedReader(Reader inputReader)*

  • Reading Characters/* Use a BufferedReader to read characters from the console.*/import java.io.*;class ReadChars {public static void main(String ar[])throws IOException{ char c; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter characters,.'to quit."); // read characters do {c = (char) br.read();System.out.println(c); } while(c != .');}}

    *

  • Reading StringsTo read a string from the keyboard, use the version of readLine( ) that is a member of the BufferedReader class.

    import java.io.*;class ReadStr { public static void main(String ar[])throws IOException{// create a BufferedReader using System.inBufferedReader 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
  • Console Output Using Character StreamsPrintWriter is one of the character-based classes for console output which makes easier to internationalize your program.One of the constructor which we can use is,PrintWriter(OutputStream outputStream, boolean flushOnNewline)PrintWriter supports the print( ) and println( ) methods for all types including Object.If an argument is not a primitive type, the PrintWriter methods will call the objects toString( ) method and then print out the result.

    *

  • Example// Demonstrate PrintWriter.import java.io.*;public class PrintWriterDemo { public static void main(String args[]) {PrintWriter pw=new PrintWriter(System.out, true);int i = 10;double d = 123.65;pw.println("Using a PrintWriter.");pw.println(i);pw.println(d);pw.println(i + " + " + d + " is " + (i+d)); }}*

  • File I/O Byte StreamsTo create a byte stream linked to a file, use FileInputStream or FileOutputStream.To open a file, simply create an object of one of these classes, specifying the name of the file as an argument to the constructor.FileInputStream(String fileName)throws FileNotFoundExceptionFileOutputStream(String fileName) throws FileNotFoundExceptionWhen you are done with a file, you should close it by calling close( ). void close() throws IOException

    *

  • To read from a file, you can use a version of read( ) that is defined within FileInputStream.int read() throws IOException

    Each time it is called, read( ) reads a single byte from the file and returns it as an integer value.

    It returns 1 when the end of the file is encountered.Reading from File Using Byte Streams*

  • Exampleimport 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 encountereddo {i = fin.read();if(i != -1) System.out.print((char) i);} while(i != -1);fin.close();}}

    *

  • Another most commonly used constructor is FileOutputStream(String fileName, boolean append) throws FileNotFoundException

    To write to a file, you will use the write( ) method.void write(int byteval) throws IOException

    Although byteval is declared as an integer, only the low-order 8 bits are written to the file.Writing to File Using Byte Streams*

  • Exampleimport java.io.*;class CopyFile {public static void main(String args[])throws IOException{ int i; FileInputStream fin; FileOutputStream fout; try { // open input filetry {fin = new FileInputStream(args[0]);}*

  • catch(FileNotFoundException e) {System.out.println("Input File Not Found");return;}try {// open output filefout = 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;}// Copy Filetry {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();}}

    Execute this program by giving in command line like as followsjava CopyFile ONE.TXT TWO.TXT

    *

  • File I/O Character StreamsFileWriter creates a Writer that you can use to write to a file.FileWriter(String fileName) throws IOException

    FileWriter(String fileName, boolean append) throws IOException

    The FileReader class creates a Reader that you can use to read the contents of a file.FileReader(String fileName) throws FileNotFoundException*

  • FileWriterimport java.io.*;

    class FWDemo {public static void main(String args[])throws IOException{String str;FileWriter fw;BufferedReader br = new BufferedReader(new InputStreamReader(System.in));try {fw = new FileWriter("test.txt");}catch(IOException exc) {

    *

  • System.out.println("Cannot open file.");return ; }System.out.println("Enter text stop to quit");do {System.out.print(": ");str = br.readLine();if(str.compareTo("stop") == 0) break;str = str + "\r\n"; // add newlinefw.write(str);} while(str.compareTo("stop") != 0);fw.close(); }}*

  • FileReaderimport java.io.*;

    class FRDemo{public static void main(String args[]) throws Exception { FileReader fr = new FileReader("test.txt"); BufferedReader br = new BufferedReader(fr); String s; while((s = br.readLine()) != null) {System.out.println(s); } fr.close();}}*

    *