18 file handling
This presentation is the property of its rightful owner.
Sponsored Links
1 / 19

18 File handling PowerPoint PPT Presentation


  • 76 Views
  • Uploaded on
  • Presentation posted in: General

18 File handling. CE00858-1: Fundamental Programming Techniques. Objectives. In this lecture, we will: open files for input and output close files after processing read data from file write results to file. Why use files?. the data in programs written so far has either been:

Download Presentation

18 File handling

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript


18 file handling

18 File handling

CE00858-1:

Fundamental Programming Techniques

18 File handling


Objectives

Objectives

In this lecture, we will:

  • open files for input and output

  • close files after processing

  • read data from file

  • write results to file

18 File handling


Why use files

Why use files?

  • the data in programs written so far has either been:

    • hard coded into the program

    • read from the keyboard using a Scanner object

  • more useful to:

    • read data from file

    • store results in a file

int width = 4;

Scanner kybd = new Scanner(System.in);

width = kybd.nextInt();

18 File handling


Using input files

Using input files

  • must import java.io.*

  • create a Scanner object to read from a file

    • need the name of the file to read in place of System.in

    • file must be in same folder as Java program or checked exception will occur

    • checked exception must be handled

    • can have any number of Scanner objects

      • one to read from each file

      • one to read from keyboard

  • when processing done all files should be closed

18 File handling


Reading from file

Reading from file

  • Scanner object methods are used to read from file in same way as they read from keyboard:

    • nextInt()

    • nextDouble()

    • next()

    • nextLine()

  • hasNext() method:

    • returns true if there is more data to read

    • returns false when end of file is reached

    • can use hasNext() method in a while loop to process all data in a file

18 File handling


Using input files example averageage

Using input files example - AverageAge

  • program to read in names and ages from a data file called in.txt

    • calculate and output the average age to the screen

    • assume that all data is valid

18 File handling


Averageage analysis

AverageAge analysis

  • what data is used?

    • sum: double calculated in program to total ages

    • count: integer calculated in program to count number of people

    • age: double input from file

    • name: string input from file

  • what operations are needed?

    • iteration to process contents of file

  • what operations are performed once before the loop?

    • create Scanner and link it to in.txt

    • initialise count and sum to 0

  • how many times is the loop performed?

    • loop performed until end of file reached

18 File handling


Averageage analysis continued

AverageAge analysis continued

  • what operations are repeated inside the loop?

    • read name and age

    • add age to sum

    • add 1 to count

  • what operations are performed once after the loop

    • close in.txt

    • calculate and output average

  • what exceptions may occur

    • file not found

    • error reading from file

    • division by 0 if no data input

18 File handling


18 file handling

AverageAge.java

//input ages from file and calculate average

import java.util.*;

import java.io.*;

public class AverageAge

{

public static void main (String [] args)

{

double sum = 0;

int count = 0;

try

{

//create Scanner linked to input file

Scanner in = new Scanner(new File("in.txt"));

String name;

double age;

continued on next slide

18 File handling


18 file handling

//read until end of file reached

while (in.hasNext())

{

name = in.next();

age = in.nextDouble();

sum = sum + age;

count++;

}

//close file

in.close();

double average = sum / count;

System.out.println("The average age is: " + average);

}

//handle any errors

catch(ArithmeticException e)

{

System.out.println("Cannot calculate average - no data");

}

catch(IOException e)

{

System.out.println("Error reading from file");

}

}

}

18 File handling


Using output files

Using output files

  • must import java.io.*

  • create a PrintWriter object to write to a file

    • need the name of the file to write to

    • file will be in same folder as Java program

      • if file already exists contents will be overwritten

      • if file doesn't exist, new one is created

    • checked exception must be handled

  • can have any number of PrintWriter objects

18 File handling


Writing to file

Writing to file

  • PrintWriter object methods are used to write data to file:

    • print()

    • println()

    • printf()

18 File handling


Using output files example oddsevens

Using output files example - OddsEvens

  • program to read in positive integers entered at the keyboard until -1 is entered

    • output all even numbers to a file called even.txt

    • output all odd numbers to a file called odd.txt

    • assume that all data is valid

18 File handling


Oddsevens analysis

OddsEvens analysis

  • what data is used?

    • num: integer input by user

  • what operations are performed?

    • iteration to process all numbers input

  • what operations are performed once before the loop?

    • create PrintWriter and link it to even.txt

    • create PrintWriter and link it to odd.txt

    • read num

  • how many times is the loop performed?

    • loop performed until -1 entered

18 File handling


Oddsevens analysis continued

OddsEvens analysis continued

  • what operations are repeated inside the loop?

    • output num to even.txt if even

    • output num to odd.txt if odd

    • read num

  • what operations are performed once after the loop

    • close even.txt and odd.txt

  • what exceptions may occur

    • error writing to file

18 File handling


18 file handling

OddsEvens.java

//input numbers and output odd ones to odd.txt, even ones to even.txt

import java.util.*;

import java.io.*;

public class OddsEvens

{

public static void main (String [] args)

{

try

{

//create PrintWriters linked to output files

Scanner kybd = new Scanner(System.in);

PrintWriter even = new PrintWriter("even.txt");

PrintWriter odd = new PrintWriter("odd.txt");

int num = kybd.nextInt();

//read until -1 entered

while (num != -1)

{

continued on next slide

18 File handling


18 file handling

if (num % 2 != 0)

{

odd.println(num);

}

else

{

even.println(num);

}

num = kybd.nextInt();

}

//close files

odd.close();

even.close();

}

catch(IOException e)

{

System.out.println("Error writing to file");

}

}

}

18 File handling


Handling exceptions

Handling exceptions

  • opening, reading, writing and closing files can generate a checked exception

  • if these are not handled, the compiler generates an error

18 File handling


Summary

Summary

In this session we have:

  • opened and closed files

  • read data from a file

  • written results to a file

18 File handling


  • Login