Topic08 Files IO

download Topic08 Files IO

of 13

Transcript of Topic08 Files IO

  • 8/11/2019 Topic08 Files IO

    1/13

    9/11/2012

    1

    CSC238 OOP

    Topic 08: FILES INPUT/OUTPUT

    Introduction The values of data structures in a program are lost when the

    program terminates

    If you want to keep the data after the program terminates, the data

    JAVA program can read a data and write a data from and to a file.

    This process is called File Input/Output (I/O)

    To store and retrieve data on a file in JAVA, it needs :1. File

    Any collection of data stored under a common name on a storage

    medium other than memory is called data file, and it is referred to

    as external file name.

    2. File stream object

    One-way transmission path that is used to connect a file stored on

    a physical device such as disk to a program.

    Each stream has its own mode whether the path will move thedata from a file into a program or from a program to a file

  • 8/11/2019 Topic08 Files IO

    2/13

  • 8/11/2019 Topic08 Files IO

    3/13

    9/11/2012

    3

    The File class5

    Every file is placed in a directory in the file system.

    The complete file name consists of the directory path and the file name.

    For example, c:\temp\Welcome.java is the complete file name for the fileWelcome.java on the windows operating system.

    The File class contains the methods for obtaining file properties and forrenaming and deleting files. However, the File class does not contain themethods for reading and writing file contents.

    e ename s a s r ng. e e c ass s a wrapper c ass or e enameand its directory path.

    For example, new File(c:\\temp) creates a File object for the directoryc:\temp, and new File(c:\\temp\\test.txt) creates a File object for the filec:\\temp\\test.txt, both on Windows.

    Example: File class6

    import java.io.*;import java.util.*;

    public class TestFileClass {public static void main(String[] args){

    //create a File object" "e e = new e c: temp ct.txt ;

    System.out.println("Does it exist? " + file .exists());//return true if the file or the directory represented by the File object existsSystem.out.println("Can it be read? " + file.canRead());//return true if the file represented by the File object exists and can be read

    System.out.println("Can it be written? " + file.canWrite());//return true if the file represented by the File object exists and can be written

    System.out.println("Is it a directory? " + file.isDirectory()); //return true if the File object represents a directorySystem.out.println("Is it a file? " + file.isFile());//return true if the File object represents a fileSystem.out.println("Is it absolute? " + file.isAbsolute());// return true if File object is created using an absolute path nameSystem.out.println("Is it hidden? " + file.isHidden());//return true if the file represented in the File object is hidden

    System.out.println("What is its absolute path? " + file.getAbsolutePath());//return the complete absolute file or directory name represented by the File object

    System.out.println("What is its name? " + file.getName());//return the last name of the complete directory and file name represented by the File object

    System.out.println("What is its path? " + file.getPath());//return the complete directory and file name represented by the File objectSystem.out.println("When was it last modified? " + new Date(file.lastModified()));//return the time that the file was last modified

    }}

  • 8/11/2019 Topic08 Files IO

    4/13

    9/11/2012

    4

    Procedure of File I/O

    Open a I/O stream objects (using Fi l eReaderor Fi l eWr i t er class)

    read() or wr i t e( ) methods)

    Close the I/O stream objects (using cl ose( )

    method)

    o e:these 3 statements are of typed checked exceptions f rom

    IOException class. So you need to handle or declare the

    IOException exception.

    Buffering

    When transferring data between program and a fileusing a buffered stream, it provides a storage area thatare used by the data as they are transferred toenhance I/O speed and performance.

    Buffered object stream are created from buffered stream

    classes. The basic I/O stream object must be created firstbefore you create a buffered object stream.

    Example :

    Fi l eReader f r = new Fi l eReader ( pr i ce. t xt ) ;

    Buf f er edReader br = new Buf f er edReader ( f r ) ;

    Fi l eWr i t er wr = new Fi l eWr i t er ( out . t xt );

    Buf f er edWr i t er br = new Buf f er edWr i t er ( f r ) ;

  • 8/11/2019 Topic08 Files IO

    5/13

    9/11/2012

    5

    Reading and Writing Character-Based Files

    Character-Based Output Stream ClassesClass Type Comments Common Methods

    FileWriter Basic output Basic stream used for write(), flush(), close()

    Character-Based Input Stream Classes

    c arac e r- ase ou pu

    BufferedWriter Buffering Provides output buffering,

    which typically improves

    performance

    write(), flush(), close()

    PrintWriter Processing Provides a number of

    useful output methods

    flush(), close(),

    print(..), println(.)

    Class Type Comments Common Methods

    FileReader Basic Input Basic stream used for

    character-based input

    read()

    BufferedReader Processing Provides buffering,

    which typically improves

    performance

    read(), readLine(), close()

    Example of Writing Character-based file

    import javax.swing.*;

    import java.io.*;

    class WriteTextFile {

    public static void main(String[] args) {

    try

    {

    String input = JOptionPane.showInputDialog("Enter the file name:");

    String fileName = input.trim();

    FileWriter fw = new FileWriter(fileName);

    BufferedWriter bw = new BufferedWriter(fw );PrintWriter pw = new PrintWriter(bw );

    for(int i=1; i

  • 8/11/2019 Topic08 Files IO

    6/13

    9/11/2012

    6

    Example of Reading Character-based file

    import java.io.*;

    class ReadTextFile {

    public static void main ( String[] args ) {

    String fileName = "thetest.txt";

    int test;

    Input file: thetest.txt

    FileReader fr = new FileReader(fileName);

    BufferedReader br = new BufferedReader(fr);

    String input = null;

    while( (input=br.readLine()) != null) {

    test = Integer.parseInt(input);

    System.out.println("Result is : "+(test));

    }

    br.close();

    }

    output

    catc e ot oun xcept on e

    { System.out.println("Problem :"+e.getMessage()); }

    catch (IOException ioe)

    { System.out.println("Problem :"+ioe.getMessage()); }

    }

    }

    Reading Character-Based file using String

    Tokenizer

    String Tokenizer

    A class that helps programmer separates individual part of a string

    if the items are separated by one character, such as a comma.

    It helps the programmer when the program reads textual data from

    a file.

    For example: Data file contains a list of grocerys list.

    A stringtokenizer object can help programmer to pullout

    apples,milk,butter,cakeflour,sugar,cereal

    apples,butter and place them in separate variables.

    The java.util.StringTokenizer class is used to break strings into tokens

    (words, numbers, operators, or whatever).

    Tokens: the data of interest in a string of characters. They maybe

    separated by a comma, a space, or one other special character.

  • 8/11/2019 Topic08 Files IO

    7/13

    9/11/2012

    7

    Reading Character-Based file using String

    Tokenizer

    A StringTokenizer constructor takes a string to break into tokens and

    returns a StringTokenizer object for that string. Each time its

    nextToken() method is called, it returns the next token in that string. If

    ' ,

    default.

    Common methods used in String Tokenizer :

    Assume that st is a StringTokenizer.

    st.hasMoreTokens() -- Returns true if there are more tokens.

    st.nextToken() -- Returns the next token as a String. st.countTokens() -- Returns the int number of tokens.

    Example : using String Tokenizerimport java.io.*;

    import java.util.*;

    class ReadTextFile2 {

    public static void main ( String[] args ) {

    String fileName = "grocery.txt";

    int num;

    try {

    FileReader fr = new FileReader(fileName);

    Input file: grocery.txt

    u = w u ;

    String input = null;

    int cnt=0;

    while( (input=br.readLine()) != null) {

    StringTokenizer st = new StringTokenizer(input, ",");cnt++;

    System.out.println(cnt + " record");

    while (st.hasMoreTokens()) {

    String w = st.nextToken();

    System.out.println(w);

    }

    }

    br.close();

    }

    catch (FileNotFoundException e)

    { System.out.println("Problem :"+e.getMessage()); }

    catch (IOException ioe)

    { System.out.println("Problem :"+ioe.getMessage()); }

    }

    }

  • 8/11/2019 Topic08 Files IO

    8/13

    9/11/2012

    8

    Scanner Class

    Using Scanner for Input from file

    The Scanner class is a class inj ava. ut i l , which allows the user to read

    values of various types.

    The Scanner looks for tokens in the input.

    to en is a series o c aracters t at en s wit w at Java ca s w itespace.A whitespace character can be a blank, a tab character, a carriage return,or the end of the file.

    Thus, if we read a line that has a series of numbers separated by blanks,the scanner will take each number as a separate token.

    Whitespace characters (blanks or carriage returns) act as separators. The next

    method returns the next input value as a string, regardless of what is keyed.

  • 8/11/2019 Topic08 Files IO

    9/13

    9/11/2012

    9

    Using Scanner for Input from file

    Reading from the keyboard using Scanner

    Scanner i n = new Scanner( Syst em. i n);

    ,with a Fi l eReader object rather than Syst em. i n.

    Scanner i nFi l e = new Scanner( new Fi l eReader ( ( "i nFi l e. dat ") ) ;

    Although all of the methods applied to keyboard input can be applied to file input,there are methods that are usually applied only to files.

    These are the methods that ask of there are more values in the file. If there are nomore values in a file, we say that the file is at the end of the file (EOF). For

    example :i nFi l e. hasNext( ) ; //returns true if inFile has another token in the file

    i nFi l e. hasNext Li ne( ) ; //returns true if inFile has another line the file

    Be sure to close all files. If you forget to close Syst em. i n, no harm is done, but

    forgetting to close a file can cause problems.

    Example : Using Scanner for Input from file

    import java.io.*;import java.util.*;

    class readScanner {

    public static void main ( String[] args ) {//String fileName = "inFile.dat";

    Input file: inFile.dat

    int test;

    try {

    Scanner inFile = new Scanner(new FileReader("inFile.dat"));

    while(inFile.hasNextLine()) {String name = inFile.next();int mark = inFile.nextInt();

    System.out.println(name+" "+mark);

    }inFile.close();

    output

    }

    catch (FileNotFoundException e){ System.out.println("Problem :"+e.getMessage()); }

    catch (IOException ioe){ System.out.println("Problem :"+ioe.getMessage()); }

    }

    }

  • 8/11/2019 Topic08 Files IO

    10/13

    9/11/2012

    10

    Exce tion handlin

    Introduction

    Exception handling is used to deal with runtime errors

    Exception may occur for various reasons such as:

    The program may attempt to open a file that doesntexist

    Network connection may hang up

    The program may attempt to access an out of bounds

    A Java exception is an instance of a class derived

    from Throwable class which contained in thejava.lang package and subclasses of Throwable arecontained in various packages

  • 8/11/2019 Topic08 Files IO

    11/13

    9/11/2012

    11

    Some of Javas Exception Classes

    Handling exception

    3 statements

    try

    Identifies a block of statements within which an exce tionmight be thrown

    catch

    Must be associated with a try statement and identifies ablock of statements that can handle a particular type ofexception occurs within the try block

    Used to execute some code if an exception occurs or iscaught

    Must be associated with a try statement and identifies ablock of statements that are executed regardless whetheror not an error occurs within the try block

  • 8/11/2019 Topic08 Files IO

    12/13

    9/11/2012

    12

    Example

    Binary I/O classes

    InputStream is the root for binary input classes andOutputStream is the root for binary output classes

  • 8/11/2019 Topic08 Files IO

    13/13

    9/11/2012

    13

    FileInputStream/FileOutputStream

    For reading/writing bytes from/to a file

    Exercise

    Application of StringTokenizer class to divide one statement

    into several words Write a program to read from a file name score.txt which

    contains several numbers shown as follows:

    Write the output to calculate the total score for each student toa text file name scoreout.txt shown as follows: