File Handling in Java January 19

Slides:



Advertisements
Similar presentations
Java File I/O. File I/O is important! Being able to write and read from files is necessary and is also one common practice of a programmer. Examples include.
Advertisements

CS102--Object Oriented Programming
More Java Syntax. Scanner class Revisited The Scanner class is a class in java.util, which allows the user to read values of various types. There are.
Text File I/O. Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with an editor are called.
File I/O and Exceptions File I/O Exceptions Throwing Exceptions Try statement and catch / finally clauses Checked and unchecked exceptions Throws clause.
Files. Advantages of files Can edit data, prepare ahead of time Can rerun file without reentering data Can examine output at leisure Can display output.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Files and Streams CS 21a Chapter 11 of Horstmann.
18 File handling1June File handling CE : Fundamental Programming Techniques.
1 CSE 142 Lecture Notes File input using Scanner Suggested reading: , Suggested self-checks: Section 6.7 # 1-11, These lecture.
File I/O There’s more to life than the keyboard. Interactive vs. file I/O All of the programs we have seen or written thus far have assumed interaction.
CS102--Object Oriented Programming Lecture 14: – File I/O BufferedReader The File class Write to /read from Binary files Copyright © 2008 Xiaoyan Li.
Strings and File I/O. Strings Java String objects are immutable Common methods include: –boolean equalsIgnoreCase(String str) –String toLowerCase() –String.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
Chapter 7: User-Defined Methods
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
Copyright 2008 by Pearson Education Building Java Programs Chapter 3 Lecture 3-3: Interactive Programs w/ Scanner reading: self-check: #16-19.
Conditional If Week 3. Lecture outcomes Boolean operators – == (equal ) – OR (||) – AND (&&) If statements User input vs command line arguments.
1 Introduction to Java Brief history of Java Sample Java Program Compiling & Executing Reading: => Section 1.1.
Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
Files. Advantages of files Can edit data, prepare ahead of time Can rerun file without reentering data Can examine output at leisure Can display output.
Reading External Files By: Greg Patterson APCS 2010.
File Input/Output. 2Java Programming: From Problem Analysis to Program Design, 3e File Input/Output File: area in secondary storage used to hold information.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
Lecture 2 Objectives Learn about objects and reference variables.
CMSC 202 Text File I/O. Aug 8, Text Files and Binary Files Files that are designed to be read by human beings, and that can be read or written with.
5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Using the while-statement to process data files. General procedure to access a data file General procedure in computer programming to read data from a.
BHCSI Programming Contests. Three contests Mock Contest #1  Friday, July 16 th  2:15 – 4:45pm UCF High School Online Contest  Thursday, July 22 nd.
1 / 65 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 12 Programming Fundamentals using Java 1.
CSC Java Programming, Fall, 2008 Week 3: Objects, Classes, Strings, Text I/O, September 11.
COMP 110: Spring Announcements Program 5 Milestone 1 was due today Program 4 has been graded.
File Input & Output Sections Outcomes  Know the difference between files and streams  Use a Scanner to read from a file  add “throws” annotations.
Copyright 2008 by Pearson Education Building Java Programs Chapter 3 Lecture 3-3: Interactive Programs w/ Scanner reading: self-check: #16-19.
1 Text File Input and Output. Objectives You will be able to Write text files from your Java programs. Read text files in your Java programs. 2.
Variable scope. Variable Scope Variables do not live forever. Failing to take that into account leads to problems. Let's look at an example. Let's write.
Lecture 4 – Scanner & Style
Sophomore Scholars Java
Chapter 2 Clarifications
CSC111 Quick Revision.
File - CIS 1068 Program Design and Abstraction
File Input / Output.
Streams & File Input/Output (I/O)
CMSC 202 Text File I/O.
Introduction to programming in java
Java Programming Lecture 2
Reading from a file A file is typically stored on your computers hard drive. In the simplest case, lets just assume it is text. For a program to use.
Exceptions and User Input Validation
Streams and File I/O.
CSC 222: Object-Oriented Programming Fall 2017
Building Java Programs
Chapter 5: Control Structures II
Chapter 5: Control Structures II
Control Statement Examples
Python I/O.
CSS 161: Fundamentals of Computing
Fundamental Error Handling
Fundamentals of Data Structures
CMSC 202 Exceptions 2nd Lecture.
CMSC 202 Exceptions 2nd Lecture.
Building Java Programs
Building Java Programs
Lecture 11 Objectives Learn what an exception is.
CMSC 202 Exceptions 2nd Lecture.
CSC1401 Input and Output (with Files)
មជ្ឈមណ្ឌលកូរ៉េ សហ្វវែរ អេច អ ឌី
CMSC 202 Exceptions 2nd Lecture.
Streams A stream is an object that enables the flow of data between a program and some I/O device or file If the data flows into a program, then the stream.
How to Run a Java Program
Presentation transcript:

File Handling in Java January 19 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. January 19

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 January 19

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 January 19

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 January 19

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

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)); January 19

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 January 19

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

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

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 January 19

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

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

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 January 19

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 January 19

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 January 19

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 January 19