Io Java Ver2

download Io Java Ver2

of 32

Transcript of Io Java Ver2

  • 7/28/2019 Io Java Ver2

    1/32

    I/O Basics

    22 April 2013

  • 7/28/2019 Io Java Ver2

    2/32

    Aside from print( ) and println( ), none of the

    I/O methods have been used significantly. The

    reason is simple: most real applications of Javaare not text-based, console programs.

    they are graphically oriented programs that rely

    upon Javas Abstract Window Toolkit (AWT) forinteraction with the user.

    Javas support for console I/O is limited andsomewhat awkward to use even in simple

    example programs. Text-based console I/O is

    just not very important to Java programming.

    22 April 2013 2

  • 7/28/2019 Io Java Ver2

    3/32

    Streams Java programs perform I/O through streams.

    A stream is an abstraction that eitherproduces or

    consumes information.

    A stream is linked to a physical device by the Java

    I/O system. All streams behave in the same manner, even if the

    actual physical devices to which they are linked

    differ.

    Same I/O classes and methods can be applied to

    any type of device.

    22 April 2013 3

  • 7/28/2019 Io Java Ver2

    4/32

    Streams(contd.) Input stream can abstract many different kinds of

    input: from a disk file, a keyboard, or a networksocket.

    Output stream may refer to the console, a disk file,

    or a network connection. Streams deal with input/output without having every

    part of your code understand the difference

    between a keyboard and a network.

    Java implements streams within class hierarchiesdefined in thejava.io package.

    22 April 2013 4

  • 7/28/2019 Io Java Ver2

    5/32

    Byte Streams and Character Streams Java 2 defines two types of streams: byte and

    character. Byte streams providemeans for handling input and

    output of bytes and are used for reading or writing

    binary data.

    Character streams handle input and output ofcharacters. They use Unicode and, therefore, can

    be internationalized.

    In some cases, character streams are more efficientthan byte streams.

    At the lowest level, all I/O is byte-oriented

    22 April 2013 5

  • 7/28/2019 Io Java Ver2

    6/32

    The Byte Stream Classes

    Byte streams are defined by using two class

    hierarchies. At the top are two abstract classes:InputStream and OutputStream.

    Each of these abstract classes has several concrete

    subclasses, that handle the differences between

    various devices, such as disk files, networkconnections, and even memory buffers.

    to use the stream classes, you must importjava.io.

    The abstract classes InputStream andOutputStream define several key methods that the

    other stream classes implement. Two of the most

    important are read( ) and write( ),

    22 April 2013 6

  • 7/28/2019 Io Java Ver2

    7/32

    which, respectively, read and write bytes of data.

    Both methods are declared as abstract inside

    InputStream and OutputStream.

    They are overridden by derived stream classes.

    The Character Stream Classes

    Character streams are defined by using two class

    hierarchies.

    At the top are two abstract classes, Readerand

    Writer, which define several key methods that theother stream classes implement.

    22 April 2013 7

  • 7/28/2019 Io Java Ver2

    8/32

    These abstract classes handle Unicode character

    streams.

    Java has several concrete subclasses of each ofthese.

    Two of the most important methods are read( ) and

    write( ), which read and write characters of data,

    respectively.

    These methods are overridden by derived stream

    classes

    First slide is Byte Stream classes Second slide is the character stream I/O classes

    22 April 2013 8

  • 7/28/2019 Io Java Ver2

    9/32

    22 April 2013 9

  • 7/28/2019 Io Java Ver2

    10/32

    22 April 2013 10

  • 7/28/2019 Io Java Ver2

    11/32

    The Predefined Streams java.lang package defines a class called System,

    which encapsulates several aspects of the run-timeenvironment.

    Using some of its methods, you can do the settings

    of various properties associated with the system. System also contains three predefined stream

    variables, in, out, and err.

    These fields are declared as public, static and final

    within System.

    They can be used by any other part of the program

    and without reference to a specific System object.

    22 April 2013 11

  • 7/28/2019 Io Java Ver2

    12/32

    System.out refers to the standard output stream. By

    default, this is the console.

    System.in refers to standard input, which is the

    keyboard by default.

    System.errrefers to the standard error stream, which

    also is the console by default.

    These streams may be redirected to any compatibleI/O device.

    System.in is an object of type InputStream

    System.out and System.errare objects of typePrintStream.

    These are byte streams, used to read and write

    characters from and to the console.

    22 April 2013 12

  • 7/28/2019 Io Java Ver2

    13/32

    Reading Console Input Console input is accomplished by reading from

    System.in. To obtain character-based stream that is attached to

    the console, you wrap System.in in a

    BufferedReaderobject.

    BuffereredReadersupports a buffered input stream.

    Constructor is shown here:

    BufferedReader(ReaderinputReader)

    22 April 2013 13

  • 7/28/2019 Io Java Ver2

    14/32

  • 7/28/2019 Io Java Ver2

    15/32

    System.in refers to an object of type InputStream,

    it can be used forinputStream.

    The following line of code creates aBufferedReaderthat is connected to the keyboard: BufferedReader br = new BufferedReader(new

    InputStreamReader(System.in));

    After this statement executes, bris a character-based stream that is linked to the console through

    System.in.

    22 April 2013 15

  • 7/28/2019 Io Java Ver2

    16/32

    Reading Characters

    To read a character from a BufferedReader, use

    read( ).

    int read( ) throws IOException

    It reads a character from the input stream and

    returns it as an integer value.

    It returns1 when the end of the stream isencountered. It can throw an IOException.

    22 April 2013 16

  • 7/28/2019 Io Java Ver2

    17/32

    // Use a BufferedReader to read characters from the console.

    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 charactersdo {

    c = (char) br.read();

    System.out.println(c);

    } while(c != 'q');}

    }

    22 April 2013 17

  • 7/28/2019 Io Java Ver2

    18/32

    Enter characters, 'q' to quit.

    123abcq

    1

    2

    3

    a

    bc

    q

    System.in is line buffered, by default. This means that no

    input is actually passed to the program until you pressENTER.

    22 April 2013 18

  • 7/28/2019 Io Java Ver2

    19/32

  • 7/28/2019 Io Java Ver2

    20/32

    //Read a string from console using a BufferedReader

    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"));

    }

    }

    22 April 2013 20

  • 7/28/2019 Io Java Ver2

    21/32

    import java.io.*; //A tiny Editor

    class TinyEdit {

    public static void main(String args[]) 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

  • 7/28/2019 Io Java Ver2

    22/32

  • 7/28/2019 Io Java Ver2

    23/32

    Here is a sample run:

    Enter lines of text.

    Enter 'stop' to quit.This is line one.

    This is line two.

    Just create String objects.stop

    Here is your file:

    This is line one.

    This is line two.

    Just create String objects

    22 April 2013 23

  • 7/28/2019 Io Java Ver2

    24/32

    Writing Console Output

    PrintStream is an output stream derived fromOutputStream, it implements the low-level

    method write( ).

    write( ) can be used to write to the console:

    void write(int byteval)

    This method writes to the stream the byte

    specified by byteval.

    byteval is declared as an integer, only the low-order eight bits are written.

    22 April 2013 24

  • 7/28/2019 Io Java Ver2

    25/32

    class WriteDemo {

    public static void main(String args[]) {

    int b;

    b = 'A';

    System.out.write(b);

    System.out.write('\n');

    }

    }

    Writes A to the console and adds a new line.

    22 April 2013 25

  • 7/28/2019 Io Java Ver2

    26/32

    Reading and Writing Files In Java, all files are byte-oriented

    FileInputStream and FileOutputStream create bytestreams linked to files

    To open a file, create an object of one of these classes,

    specifying the name of the file as an argument to the

    constructor

    FileInputStream (String fileName) throws

    FileNotFoundException

    FileOutputStream (String fileName) throws

    FileNotFoundException

    void close( ) throws IOException

    int read( ) throws IOException

    22 April 2013 26

  • 7/28/2019 Io Java Ver2

    27/32

    /* Display a text file. Specify the name of the file that you want

    to see. For example, to see a file called TEST.TXT, use the

    following command line.

    java ShowFile TEST.TXT */

    import java.io.*;

    class ShowFile {

    public static void main(String args[]) throws IOException {

    int i;

    FileInputStream fin;

    22 April 2013 27

  • 7/28/2019 Io Java Ver2

    28/32

    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( );

    }

    }22 April 2013 28

  • 7/28/2019 Io Java Ver2

    29/32

    To write to a file, use write( ) method defined by

    FileOutputStream.

    void write(int byteval) throws IOException

    /* Copy a text file. To use this program, specify the name of the

    source file and the destination file.

    For example, to copy a file called FIRST.TXT to a file calledSECOND.TXT, use the following command line.

    java CopyFile FIRST.TXT SECOND.TXT

    */

    22 April 2013 29

  • 7/28/2019 Io Java Ver2

    30/32

    import java.io.*;

    class CopyFile {

    public static void main(String args[]) throws IOException {

    int i;FileInputStream fin;

    FileOutputStream fout;

    try {

    //open input file

    try {

    fin = new FileInputStream(args[0]);

    } catch(FileNotFoundException e) {

    System.out.println("Input File Not Found");

    return;}

    22 April 2013 30

  • 7/28/2019 Io Java Ver2

    31/32

    //open output file

    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;

    }

    22 April 2013 31

  • 7/28/2019 Io Java Ver2

    32/32

    //Copy File

    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();}

    }

    22 April 2013 32