SlideShare a Scribd company logo
File Handling


               OOSSE - Programming with Java
                        Lecture A1




Dec 21, 2012    OOSSE - Java Lecture A1    1
Objectives
 In this lecture, we will:
     – learn how to read data from a file
     – learn how to write data to a file
     – discuss the structure of a program which uses files




Dec 21, 2012      OOSSE - Java Lecture A1           2
Why use files?

 • In all the programs we have written so far, any data we
   need has been either
     – hard coded into the program
     String name = "Cathy";
     – or read in from the keyboard using a Scanner object
     Scanner kybd = new Scanner(System.in);
     System.out.println("What is your name?");
     name = kybd.next();
 • It is tedious to type in all the data to be processed each time
   the program is run
 • It is not very useful if the data and results cannot be saved
     – imagine a payroll program where all information about the
       employees has to be entered each time the program is run
Dec 21, 2012     OOSSE - Java Lecture A1           3
Opening a file to read from

 • A Scanner object can be set up to read from a file
     – so far all our Scanner objects have read from the keyboard
 • The name of the file to read from is required
 • First create a File object corresponding to this file
     – need to import java.io.*
     – this is a library of java classes for input and output
 • Then create a Scanner object using the File object as the
   source of the input
     – instead of System.in
 • If the input file is in the same directory as the Java program it
   makes life easier
     – if the file is not found, there will be an error (exception) when the
       program runs


Dec 21, 2012        OOSSE - Java Lecture A1                     4
Reading from a file

  import java.util.*;
  import java.io.*;
  public class Payroll
  {
    public static void main(String args[])
    {
      String fName = "payroll.txt";
      Scanner inFile = new Scanner(new File(fName));
      ……
     or
      Scanner inFile =
               new Scanner(new File("payroll.txt"));



Dec 21, 2012   OOSSE - Java Lecture A1     5
Reading from Scanner objects

 • Once the Scanner object is created, we can use its
   methods to read from the file
     – just like when reading from the keyboard
     String name = inFile.next();
     double hourlyPay = inFile.nextDouble();
 • Multiple Scanner objects can be created, as long as they
   are given different names
     – for example, to read from two different files
     – or from a file and the keyboard
     Scanner kybd = new Scanner(System.in);
     Scanner inFile = new Scanner(new File(fName));



Dec 21, 2012   OOSSE - Java Lecture A1        6
Reading from a file
 • The hasNext() method is useful when you do not know how
   much data is in the file
     – returns true if there is more data to read
     – returns false if you have reached the end of the file
 • It can be used in a while loop to process all the data in the file
 • Imagine a text file is available where each line contains
   information about one employee:
     – name (as a String)
     – followed by hourly pay (as a double)
 • For example the file could contain the data
   Nick                  4.95
   Fred                  5.94
   Dave                  9.45
 • The code overleaf would process all the data in turn

Dec 21, 2012       OOSSE - Java Lecture A1               7
Reading all the data in a file

 while (inFile.hasNext())
 {
   name = inFile.next();
   hourlyPay = inFile.nextDouble();
   System.out.println("Hours worked by "+name+"?");
   hoursWorked = kybd.nextInt();
   double pay = hourlyPay * hoursWorked;
   System.out.println("Pay is " + pay);
 }
 inFile.close();




Dec 21, 2012   OOSSE - Java Lecture A1   8
Closing a file
 • When you have finished reading from a file, you should
   close it
 • A file is closed by calling the close() method of the
   Scanner object that was set up to read the file
     inFile.close();




Dec 21, 2012    OOSSE - Java Lecture A1       9
Tips for Input Files
 • Decide on the format of the data
     – repeating rows of
         • name (as a String)
         • followed by hourly pay (as a double)
 • Make sure the information is
     – in the correct order
     – of the correct type
 • to match the input statements in your program


 • Any text editor can be used to create and edit the file
 • or it could be output from a program
     – which writes to the file using the correct format


Dec 21, 2012       OOSSE - Java Lecture A1             10
Writing to a file

• The name of the file to write to is required
• First create a PrintWriter object for this file
   – need to import java.io.*
   – same library of java classes as FileReader
• Typically the output file will be in the same directory as the Java
  program
• If a file of this name already exists
   – it will be opened
   – all the data currently in the file will be lost
• If the file does not already exist, a new one will be created
  PrintWriter pw = new PrintWriter("Payroll.txt");



Dec 21, 2012        OOSSE - Java Lecture A1            11
Writing to a file

 • Once the PrintWriter object is created, we can use its
   methods to write to the file
     – can use print(), println(), printf()
     – just like when writing to the console output window
 • For example to print an employee’s data on one line
     pw.print(name);
     pw.printf("%6.2f", hourlyPay);
     pw.println();
 • Close the PrintWriter when you have finished writing to
   the file
     pw.close();



Dec 21, 2012      OOSSE - Java Lecture A1            12
Structure of a program that uses files
 • A program which reads data from a file may do a lot of
   processing on it
     –   do calculations (totals, averages)
     –   add to it (input by user)
     –   delete some of it
     –   sort it
     –   search all of it for a particular data value
 • It is awkward to search for and retrieve only the required
   data from a sequential file for each process
 • and to write changes back to the original file




Dec 21, 2012        OOSSE - Java Lecture A1             13
Structure of a program that uses files
 • It is sometimes better to
     – open the input file
     – read all the data in the file into an appropriate data structure
         • such as an array, or several arrays
     – close the input file
 • Do all the processing in memory, then write the final version
   of the data to a file
     – either with the same name as the input file
         • original data is lost
     – or a new file
 • Most of the program (data structures, processing) is the
   same as when all the data is entered via the keyboard
     – just add the file-reading code at the beginning of the program
     – and the file-writing code at the end

Dec 21, 2012        OOSSE - Java Lecture A1            14
Files and Exceptions
 • File handling is one area that is prone to things going
   wrong
     – A file may not exist
     – A file may not be accessible
     – The format of the data in the file may be incorrect
 • Whenever dealing with files it is best to make use of try
   catch blocks to handle any exceptions
     – Try to anticipate what could go wrong




Dec 21, 2012      OOSSE - Java Lecture A1             15
Summary
 In this lecture we have:
 • learned how to read data from a file
 • learned how to write data to a file
 • discussed the structure of a program which uses files




Dec 21, 2012    OOSSE - Java Lecture A1        16

More Related Content

What's hot

Packages in java
Packages in javaPackages in java
Packages in java
Elizabeth alexander
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
MOHIT AGARWAL
 
Wrapper class
Wrapper classWrapper class
Wrapper class
kamal kotecha
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in Java
Niloy Saha
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
SURIT DATTA
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
Nilesh Dalvi
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
Megha V
 
Interface in java
Interface in javaInterface in java
Interface in java
PhD Research Scholar
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
Naz Abdalla
 
Java Data Types
Java Data TypesJava Data Types
Java Data Types
Spotle.ai
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
kamal kotecha
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
Anton Keks
 
Java exception handling
Java exception handlingJava exception handling
Java exception handlingBHUVIJAYAVELU
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
Arzath Areeff
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
VINOTH R
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaRaghu nath
 
Java Streams
Java StreamsJava Streams
Java Streams
M Vishnuvardhan Reddy
 
6. static keyword
6. static keyword6. static keyword
6. static keyword
Indu Sharma Bhardwaj
 

What's hot (20)

Java input
Java inputJava input
Java input
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
 
OOP java
OOP javaOOP java
OOP java
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in Java
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Java Data Types
Java Data TypesJava Data Types
Java Data Types
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Java Streams
Java StreamsJava Streams
Java Streams
 
6. static keyword
6. static keyword6. static keyword
6. static keyword
 

Viewers also liked

Routing Protocols and Concepts - Chapter 1
Routing Protocols and Concepts - Chapter 1Routing Protocols and Concepts - Chapter 1
Routing Protocols and Concepts - Chapter 1CAVC
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handlingpinkpreet_kaur
 
Congestion control in TCP
Congestion control in TCPCongestion control in TCP
Congestion control in TCP
selvakumar_b1985
 
Socket System Calls
Socket System CallsSocket System Calls
Socket System Calls
Avinash Varma Kalidindi
 
TCP congestion control
TCP congestion controlTCP congestion control
TCP congestion control
Shubham Jain
 
Socket programming
Socket programmingSocket programming
Socket programming
chandramouligunnemeda
 

Viewers also liked (6)

Routing Protocols and Concepts - Chapter 1
Routing Protocols and Concepts - Chapter 1Routing Protocols and Concepts - Chapter 1
Routing Protocols and Concepts - Chapter 1
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
 
Congestion control in TCP
Congestion control in TCPCongestion control in TCP
Congestion control in TCP
 
Socket System Calls
Socket System CallsSocket System Calls
Socket System Calls
 
TCP congestion control
TCP congestion controlTCP congestion control
TCP congestion control
 
Socket programming
Socket programmingSocket programming
Socket programming
 

Similar to 14 file handling

Data file handling
Data file handlingData file handling
Data file handling
Saurabh Patel
 
ch09.ppt
ch09.pptch09.ppt
ch09.ppt
NiharikaDubey17
 
chapter-4-data-file-handlingeng.pdf
chapter-4-data-file-handlingeng.pdfchapter-4-data-file-handlingeng.pdf
chapter-4-data-file-handlingeng.pdf
SyedAhmed991492
 
ProgFund_Lecture_6_Files_and_Exception_Handling-3.pdf
ProgFund_Lecture_6_Files_and_Exception_Handling-3.pdfProgFund_Lecture_6_Files_and_Exception_Handling-3.pdf
ProgFund_Lecture_6_Files_and_Exception_Handling-3.pdf
lailoesakhan
 
File handling.pptx
File handling.pptxFile handling.pptx
File handling.pptx
VishuSaini22
 
File Handling
File HandlingFile Handling
File Handling
AlgeronTongdoTopi
 
File Handling
File HandlingFile Handling
File Handling
AlgeronTongdoTopi
 
Reading and Writing Files
Reading and Writing FilesReading and Writing Files
Reading and Writing Files
primeteacher32
 
CSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfCSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdf
VithalReddy3
 
File Handling Btech computer science and engineering ppt
File Handling Btech computer science and engineering pptFile Handling Btech computer science and engineering ppt
File Handling Btech computer science and engineering ppt
pinuadarsh04
 
FIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptxFIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptx
Ashwini Raut
 
Assets, files, and data parsing
Assets, files, and data parsingAssets, files, and data parsing
Assets, files, and data parsing
Aly Arman
 
An Introduction To Python - Files, Part 1
An Introduction To Python - Files, Part 1An Introduction To Python - Files, Part 1
An Introduction To Python - Files, Part 1
Blue Elephant Consulting
 
Linux System Programming - File I/O
Linux System Programming - File I/O Linux System Programming - File I/O
Linux System Programming - File I/O
YourHelper1
 
File handling4.pdf
File handling4.pdfFile handling4.pdf
File handling4.pdf
sulekha24
 
File handling3.pdf
File handling3.pdfFile handling3.pdf
File handling3.pdf
nishant874609
 
Pf cs102 programming-8 [file handling] (1)
Pf cs102 programming-8 [file handling] (1)Pf cs102 programming-8 [file handling] (1)
Pf cs102 programming-8 [file handling] (1)
Abdullah khawar
 
Memory management
Memory managementMemory management
Memory management
Vikash Patel
 
pointer, structure ,union and intro to file handling
 pointer, structure ,union and intro to file handling pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
Rai University
 

Similar to 14 file handling (20)

Data file handling
Data file handlingData file handling
Data file handling
 
ch09.ppt
ch09.pptch09.ppt
ch09.ppt
 
chapter-4-data-file-handlingeng.pdf
chapter-4-data-file-handlingeng.pdfchapter-4-data-file-handlingeng.pdf
chapter-4-data-file-handlingeng.pdf
 
ProgFund_Lecture_6_Files_and_Exception_Handling-3.pdf
ProgFund_Lecture_6_Files_and_Exception_Handling-3.pdfProgFund_Lecture_6_Files_and_Exception_Handling-3.pdf
ProgFund_Lecture_6_Files_and_Exception_Handling-3.pdf
 
File handling.pptx
File handling.pptxFile handling.pptx
File handling.pptx
 
File Handling
File HandlingFile Handling
File Handling
 
File Handling
File HandlingFile Handling
File Handling
 
Reading and Writing Files
Reading and Writing FilesReading and Writing Files
Reading and Writing Files
 
UNIT 5.pptx
UNIT 5.pptxUNIT 5.pptx
UNIT 5.pptx
 
CSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfCSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdf
 
File Handling Btech computer science and engineering ppt
File Handling Btech computer science and engineering pptFile Handling Btech computer science and engineering ppt
File Handling Btech computer science and engineering ppt
 
FIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptxFIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptx
 
Assets, files, and data parsing
Assets, files, and data parsingAssets, files, and data parsing
Assets, files, and data parsing
 
An Introduction To Python - Files, Part 1
An Introduction To Python - Files, Part 1An Introduction To Python - Files, Part 1
An Introduction To Python - Files, Part 1
 
Linux System Programming - File I/O
Linux System Programming - File I/O Linux System Programming - File I/O
Linux System Programming - File I/O
 
File handling4.pdf
File handling4.pdfFile handling4.pdf
File handling4.pdf
 
File handling3.pdf
File handling3.pdfFile handling3.pdf
File handling3.pdf
 
Pf cs102 programming-8 [file handling] (1)
Pf cs102 programming-8 [file handling] (1)Pf cs102 programming-8 [file handling] (1)
Pf cs102 programming-8 [file handling] (1)
 
Memory management
Memory managementMemory management
Memory management
 
pointer, structure ,union and intro to file handling
 pointer, structure ,union and intro to file handling pointer, structure ,union and intro to file handling
pointer, structure ,union and intro to file handling
 

More from APU

01 introduction to_module
01 introduction to_module01 introduction to_module
01 introduction to_moduleAPU
 
. 1. introduction to object orientation
. 1. introduction to object orientation. 1. introduction to object orientation
. 1. introduction to object orientationAPU
 
. 01 introduction_to_module
. 01 introduction_to_module. 01 introduction_to_module
. 01 introduction_to_moduleAPU
 
9. oo languages
9. oo languages9. oo languages
9. oo languagesAPU
 
8. design patterns
8. design patterns8. design patterns
8. design patternsAPU
 
7. sequence and collaboration diagrams
7. sequence and collaboration diagrams7. sequence and collaboration diagrams
7. sequence and collaboration diagramsAPU
 
6. activity diagrams
6. activity diagrams6. activity diagrams
6. activity diagramsAPU
 
5. state diagrams
5. state diagrams5. state diagrams
5. state diagramsAPU
 
4. class diagrams using uml
4. class diagrams using uml4. class diagrams using uml
4. class diagrams using umlAPU
 
3. use cases
3. use cases3. use cases
3. use casesAPU
 
01 introduction to_module
01 introduction to_module01 introduction to_module
01 introduction to_moduleAPU
 
. 9. oo languages
. 9. oo languages. 9. oo languages
. 9. oo languagesAPU
 
08 aggregation and collection classes
08  aggregation and collection classes08  aggregation and collection classes
08 aggregation and collection classesAPU
 
. 8. design patterns
. 8. design patterns. 8. design patterns
. 8. design patternsAPU
 
. 5. state diagrams
. 5. state diagrams. 5. state diagrams
. 5. state diagramsAPU
 
. 4. class diagrams using uml
. 4. class diagrams using uml. 4. class diagrams using uml
. 4. class diagrams using umlAPU
 
. 2. introduction to uml
. 2. introduction to uml. 2. introduction to uml
. 2. introduction to umlAPU
 
. 01 introduction_to_module
. 01 introduction_to_module. 01 introduction_to_module
. 01 introduction_to_moduleAPU
 
13 gui development
13 gui development13 gui development
13 gui developmentAPU
 
10 exceptionsin java
10 exceptionsin java10 exceptionsin java
10 exceptionsin javaAPU
 

More from APU (20)

01 introduction to_module
01 introduction to_module01 introduction to_module
01 introduction to_module
 
. 1. introduction to object orientation
. 1. introduction to object orientation. 1. introduction to object orientation
. 1. introduction to object orientation
 
. 01 introduction_to_module
. 01 introduction_to_module. 01 introduction_to_module
. 01 introduction_to_module
 
9. oo languages
9. oo languages9. oo languages
9. oo languages
 
8. design patterns
8. design patterns8. design patterns
8. design patterns
 
7. sequence and collaboration diagrams
7. sequence and collaboration diagrams7. sequence and collaboration diagrams
7. sequence and collaboration diagrams
 
6. activity diagrams
6. activity diagrams6. activity diagrams
6. activity diagrams
 
5. state diagrams
5. state diagrams5. state diagrams
5. state diagrams
 
4. class diagrams using uml
4. class diagrams using uml4. class diagrams using uml
4. class diagrams using uml
 
3. use cases
3. use cases3. use cases
3. use cases
 
01 introduction to_module
01 introduction to_module01 introduction to_module
01 introduction to_module
 
. 9. oo languages
. 9. oo languages. 9. oo languages
. 9. oo languages
 
08 aggregation and collection classes
08  aggregation and collection classes08  aggregation and collection classes
08 aggregation and collection classes
 
. 8. design patterns
. 8. design patterns. 8. design patterns
. 8. design patterns
 
. 5. state diagrams
. 5. state diagrams. 5. state diagrams
. 5. state diagrams
 
. 4. class diagrams using uml
. 4. class diagrams using uml. 4. class diagrams using uml
. 4. class diagrams using uml
 
. 2. introduction to uml
. 2. introduction to uml. 2. introduction to uml
. 2. introduction to uml
 
. 01 introduction_to_module
. 01 introduction_to_module. 01 introduction_to_module
. 01 introduction_to_module
 
13 gui development
13 gui development13 gui development
13 gui development
 
10 exceptionsin java
10 exceptionsin java10 exceptionsin java
10 exceptionsin java
 

14 file handling

  • 1. File Handling OOSSE - Programming with Java Lecture A1 Dec 21, 2012 OOSSE - Java Lecture A1 1
  • 2. Objectives In this lecture, we will: – learn how to read data from a file – learn how to write data to a file – discuss the structure of a program which uses files Dec 21, 2012 OOSSE - Java Lecture A1 2
  • 3. Why use files? • In all the programs we have written so far, any data we need has been either – hard coded into the program String name = "Cathy"; – or read in from the keyboard using a Scanner object Scanner kybd = new Scanner(System.in); System.out.println("What is your name?"); name = kybd.next(); • It is tedious to type in all the data to be processed each time the program is run • It is not very useful if the data and results cannot be saved – imagine a payroll program where all information about the employees has to be entered each time the program is run Dec 21, 2012 OOSSE - Java Lecture A1 3
  • 4. Opening a file to read from • A Scanner object can be set up to read from a file – so far all our Scanner objects have read from the keyboard • The name of the file to read from is required • First create a File object corresponding to this file – need to import java.io.* – this is a library of java classes for input and output • Then create a Scanner object using the File object as the source of the input – instead of System.in • If the input file is in the same directory as the Java program it makes life easier – if the file is not found, there will be an error (exception) when the program runs Dec 21, 2012 OOSSE - Java Lecture A1 4
  • 5. Reading from a file import java.util.*; import java.io.*; public class Payroll { public static void main(String args[]) { String fName = "payroll.txt"; Scanner inFile = new Scanner(new File(fName)); …… or Scanner inFile = new Scanner(new File("payroll.txt")); Dec 21, 2012 OOSSE - Java Lecture A1 5
  • 6. Reading from Scanner objects • Once the Scanner object is created, we can use its methods to read from the file – just like when reading from the keyboard String name = inFile.next(); double hourlyPay = inFile.nextDouble(); • Multiple Scanner objects can be created, as long as they are given different names – for example, to read from two different files – or from a file and the keyboard Scanner kybd = new Scanner(System.in); Scanner inFile = new Scanner(new File(fName)); Dec 21, 2012 OOSSE - Java Lecture A1 6
  • 7. Reading from a file • The hasNext() method is useful when you do not know how much data is in the file – returns true if there is more data to read – returns false if you have reached the end of the file • It can be used in a while loop to process all the data in the file • Imagine a text file is available where each line contains information about one employee: – name (as a String) – followed by hourly pay (as a double) • For example the file could contain the data Nick 4.95 Fred 5.94 Dave 9.45 • The code overleaf would process all the data in turn Dec 21, 2012 OOSSE - Java Lecture A1 7
  • 8. Reading all the data in a file while (inFile.hasNext()) { name = inFile.next(); hourlyPay = inFile.nextDouble(); System.out.println("Hours worked by "+name+"?"); hoursWorked = kybd.nextInt(); double pay = hourlyPay * hoursWorked; System.out.println("Pay is " + pay); } inFile.close(); Dec 21, 2012 OOSSE - Java Lecture A1 8
  • 9. Closing a file • When you have finished reading from a file, you should close it • A file is closed by calling the close() method of the Scanner object that was set up to read the file inFile.close(); Dec 21, 2012 OOSSE - Java Lecture A1 9
  • 10. Tips for Input Files • Decide on the format of the data – repeating rows of • name (as a String) • followed by hourly pay (as a double) • Make sure the information is – in the correct order – of the correct type • to match the input statements in your program • Any text editor can be used to create and edit the file • or it could be output from a program – which writes to the file using the correct format Dec 21, 2012 OOSSE - Java Lecture A1 10
  • 11. Writing to a file • The name of the file to write to is required • First create a PrintWriter object for this file – need to import java.io.* – same library of java classes as FileReader • Typically the output file will be in the same directory as the Java program • If a file of this name already exists – it will be opened – all the data currently in the file will be lost • If the file does not already exist, a new one will be created PrintWriter pw = new PrintWriter("Payroll.txt"); Dec 21, 2012 OOSSE - Java Lecture A1 11
  • 12. Writing to a file • Once the PrintWriter object is created, we can use its methods to write to the file – can use print(), println(), printf() – just like when writing to the console output window • For example to print an employee’s data on one line pw.print(name); pw.printf("%6.2f", hourlyPay); pw.println(); • Close the PrintWriter when you have finished writing to the file pw.close(); Dec 21, 2012 OOSSE - Java Lecture A1 12
  • 13. Structure of a program that uses files • A program which reads data from a file may do a lot of processing on it – do calculations (totals, averages) – add to it (input by user) – delete some of it – sort it – search all of it for a particular data value • It is awkward to search for and retrieve only the required data from a sequential file for each process • and to write changes back to the original file Dec 21, 2012 OOSSE - Java Lecture A1 13
  • 14. Structure of a program that uses files • It is sometimes better to – open the input file – read all the data in the file into an appropriate data structure • such as an array, or several arrays – close the input file • Do all the processing in memory, then write the final version of the data to a file – either with the same name as the input file • original data is lost – or a new file • Most of the program (data structures, processing) is the same as when all the data is entered via the keyboard – just add the file-reading code at the beginning of the program – and the file-writing code at the end Dec 21, 2012 OOSSE - Java Lecture A1 14
  • 15. Files and Exceptions • File handling is one area that is prone to things going wrong – A file may not exist – A file may not be accessible – The format of the data in the file may be incorrect • Whenever dealing with files it is best to make use of try catch blocks to handle any exceptions – Try to anticipate what could go wrong Dec 21, 2012 OOSSE - Java Lecture A1 15
  • 16. Summary In this lecture we have: • learned how to read data from a file • learned how to write data to a file • discussed the structure of a program which uses files Dec 21, 2012 OOSSE - Java Lecture A1 16

Editor's Notes

  1. Part of this lecture will be reserved for working through solutions to selected exercises from last week. Notes relating to this do not appear in the slides.