COMP 110: Spring 20091 Announcements Program 5 Milestone 1 was due today Program 4 has been graded.

Slides:



Advertisements
Similar presentations
COMP 110: Introduction to Programming Tyler Johnson Apr 13, 2009 MWF 11:00AM-12:15PM Sitterson 014.
Advertisements

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.
Chapter 10 Ch 1 – Introduction to Computers and Java Streams and File IO 1.
10-1 Writing to a Text File When a text file is opened in this way, a FileNotFoundException can be thrown – In this context it actually means that the.
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.
Files from Ch4. File Input and Output  Reentering data all the time could get tedious for the user.  The data can be saved to a file. Files can be input.
CIS 1068 Program Design and Abstraction
FIT FIT1002 Computer Programming Unit 19 File I/O and Exceptions.
Chapter 9 Streams and File I/O Overview of Streams and File I/O
Unit 201 FILE IO Types of files Opening a text file for reading Reading from a text file Opening a text file for writing/appending Writing/appending to.
Files and Streams. Goals To be able to read and write text files To be able to read and write text files To become familiar with the concepts of text.
1 Text File I/O  I/O streams  Opening a text file for reading  Closing a stream  Reading a text file  Writing and appending to a text file.
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.
1 Text File I/O Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l.
1 Streams Overview l I/O streams l Opening a text file for reading l Reading a text file l Closing a stream l Reading numbers from a text file l Writing.
7/2/2015CS2621 OO Design and Programming II I/O: Reading and Writing.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
Lecture 30 Streams and File I/O COMP1681 / SE15 Introduction to Programming.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 6: File Processing.
11 Chapter 4 LOOPS AND FILES CONT’D. 22 SENTINEL-CONTROLLED LOOPS Suppose we did not know the number of grades that were to be entered. Maybe, a single.
Streams and File I/O Chapter 14. I/O Overview I/O = Input/Output In this context it is input to and output from programs Input can be from keyboard or.
CS0007: Introduction to Computer Programming File IO and Recursion.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
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.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
1 BUILDING JAVA PROGRAMS CHAPTER 6 FILE PROCESSING.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
BUILDING JAVA PROGRAMS CHAPTER 6 File Processing.
Lecture 3 Looping and FIiling. 5-2 Topics – The Increment and Decrement Operators – The while Loop – Using the while Loop for Input Validation – The do.
Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.
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.
Chapter 10 Text Files Section 10.2 Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
CS 46B: Introduction to Data Structures June 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
 Learn about computer files  Use the Path class  Learn about  Streams  Buffers  file organization  Use Java’s IO classes to write to and read from.
1 / 65 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 12 Programming Fundamentals using Java 1.
Copyright 2010 by Pearson Education Building Java Programs Chapter 6 Lecture 6-1: File Input with Scanner reading: 6.1 – 6.2, 5.4.
File Input and Output Appendix E © 2015 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
File Input & Output Sections Outcomes  Know the difference between files and streams  Use a Scanner to read from a file  add “throws” annotations.
Lab 04-2 Objectives:  Understand what a file is.  Learn how to use the File class  Learn how to use the Scanner class to read from files  Learn about.
File Input & Output Sections Outcomes  Know the difference between files and streams  Use a Scanner to read from a file  add “throws” annotations.
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.
Building Java Programs Chapter 6 File Processing Copyright (c) Pearson All rights reserved.
For Friday Finish reading chapter 9 WebCT quiz 17.
COMP Streams and File I/O
File - CIS 1068 Program Design and Abstraction
Text File Input/Output
Streams & File Input/Output (I/O)
CMSC 202 Text File I/O.
Streams and File I/O.
Building Java Programs
Text File Input/Output
Some File I/O CS140: Introduction to Computing 1 Savitch Chapter 9.1, 10.1, /25/13.
CSS161: Fundamentals of Computing
Streams and File I/O Chapter 14.
CSS 161: Fundamentals of Computing
Building Java Programs Chapter 6
Building Java Programs Chapter 6
File I/O ICS 111: Introduction to Computer Science I
Input/output (I/O) import java.io.*;
Building Java Programs
Building Java Programs
Input/output (I/O) import java.io.*;
Input/output (I/O) import java.io.*;
Input/output (I/O) import java.io.*;
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.
Presentation transcript:

COMP 110: Spring Announcements Program 5 Milestone 1 was due today Program 4 has been graded

COMP 110: Spring Today in COMP 110 Review Exceptions Basic File I/O Programming Demo

COMP 110: Spring Review Exceptions

COMP 110: Spring Exceptions An exception is an object that signals the occurrence of an unusual (exceptional) event during program execution Exception handling is a way of detecting and dealing with these unusual cases in principled manner i.e. without a run-time error or program crash

COMP 110: Spring The try Block A try block contains the basic algorithm for when everything goes smoothly Try blocks will possibly throw an exception Syntax try { Code_To_Try } Example try { average = scoreSum/numGames; }

COMP 110: Spring The catch Block The catch block is used to deal with any exceptions that may occur This is your error handling code Syntax catch(Exception_Class_Name Catch_Block_Parameter) { Process_Exception_Of_Type_Exception_Class_Name } Possibly_Other_Catch_Blocks Example catch(ArithmeticException e) { System.out.println(e.getMessage()); System.out.println("Cannot compute average for 0 games"); }

COMP 110: Spring Example Using Exception Handling (try/catch blocks) int score = keyboard.nextInt(); int scoreSum = 0; int numGames = 0; while(score >= 0) { scoreSum += score; numGames++; score = keyboard.nextInt(); } double average = 0; try { average = scoreSum/numGames; } catch(ArithmeticException e) { System.out.println(e.getMessage()); System.out.println("Cannot compute average for 0 games"); }

COMP 110: Spring Files Your music, pictures, videos, even your Java programs are stored on your computer in files Files can also be used to store input for a program, or a program’s output

COMP 110: Spring Streams Writing to & reading from files is done using a stream A stream is a flow of data This data might be characters, numbers or bytes of binary digits Data that flows INTO your program is called an input stream Data that flows OUT of your program is called an output stream

COMP 110: Spring Streams Program Keyboard CD Input Stream Monitor Hard drive Output Stream

COMP 110: Spring Stream Class In Java, streams are objects of special stream class Scanner objects are input streams We’ve used the Scanner class to read data from the keyboard System.out is an output stream We use it to print data out to screen

COMP 110: Spring File I/O File I/O stands for File Input/Output Why use files for input/output? Permanent data storage Easy to read in large amount of data We can also read it in repeatedly Easy to output large amounts of data that can be analyzed later

COMP 110: Spring Text Files vs Binary Files All files are stored as binary digits (bits) In some cases this data is interpreted as text (text files) Your Java files Text files can be easily read/edited by humans All other files are binary files Your music & picture files Binary files cannot be easily read/edited by humans

COMP 110: Spring Creating a Text File The PrintWriter class is provided by Java to aid in creating and writing text files Need to import from java.io Before we can write to a text file, we need to connect to an output stream This is essentially opening the file, which allows us to write to it All files have a name, such as out.txt, that we use when opening the file

COMP 110: Spring Opening a Text File //need to import java.io.PrintWriter //& java.io.FileNotFoundException String fileName = "out.txt"; PrintWriter outputStream = null; try { outputStream = new PrintWriter(fileName); } catch(FileNotFoundException e) { System.out.println("Error opening file " + fileName); System.exit(0); }

COMP 110: Spring Opening a Text File outputStream = new PrintWriter(fileName); Calls the constructor of the PrintWriter class Opens the text file with the name fileName ("out.txt") If the file already exists, its contents are overwritten If the file doesn’t exist, an empty file with that name is created Since the constructor might throw a FileNotFoundException, we must enclose it in a try block Also need a corresponding catch block to catch the exception

COMP 110: Spring Writing to a Text File Once the file is open, we can write to it The PrintWriter class has methods print & println that work just like methods in System.out Data is written to the file instead of to screen Calls to these methods do not have to be within a try block outputStream.println("I’m writing to a file!"); outputStream.print("Another message!");

COMP 110: Spring Buffering When you write to a file, the data may not immediately reach its destination This is because of buffering The output stream will wait until it has collected a large amount of data to write before it writes anything to the file itself This is done for efficiency

COMP 110: Spring Closing a Text File Once you’re finished writing to the file you should disconnect the stream from the file itself This is done using the close method outputStream.close(); //close the file Calling the close() method ensures that any remaining data is written out to the file

COMP 110: Spring Example: Writing to a File import java.io.*; public class TextFileOutput { public static void main(String[] args) { String fileName = "out.txt"; PrintWriter outputStream = null; try { outputStream = new PrintWriter(fileName); } catch(FileNotFoundException e) { System.out.println("Error opening file " + fileName); System.exit(0); } //print the numbers 0-9 to the file one on each line for(int i = 0; i < 10; i++) { outputStream.println(i); } outputStream.close(); //close the file }

COMP 110: Spring Summary: Writing to a File Open the file Create a PrintWriter object Pass the name of the file you want to write to the constructor Use try/catch blocks to catch a possible FileNotFoundException Write to the file Use the print/println methods of the PrintWriter object you created Close the file

COMP 110: Spring Reading from a Text File We can read from a text file using an object of the Scanner class Recall, we have used the scanner class to read input from the keyboard, as in: Scanner keyboard = new Scanner(System.in); We can create a scanner object to read from a file in the following way String fileName = "in.txt"; Scanner inputFile = new Scanner(new File(fileName));

COMP 110: Spring Opening a File for Reading The Scanner class constructor can also throw a FileNotFoundException We must enclose it in a try block String fileName = "in.txt"; Scanner inputFile = null; try { inputFile = new Scanner(new File(fileName)); } catch(FileNotFoundException e) { System.out.println("Error opening file " + fileName); System.exit(0); }

COMP 110: Spring Reading from a Text File All methods of the Scanner class we have used previously can also be used to read from a text file nextInt(), nextDouble(), nextLine(), etc The Scanner class also has methods to determine whether more input data remains in the file hasNext(), hasNextDouble(), hasNextInt(), hasNextLine() etc.

COMP 110: Spring Read a File & Print to Screen import java.util.Scanner; import java.io.*; public class TextFileInput { public static void main(String[] args) { String fileName = "in.txt"; //the name of the file we want to open Scanner inputFile = null; try { inputFile = new Scanner(new File(fileName)); //open the file } catch(FileNotFoundException e) { System.out.println("Error opening file " + fileName); System.exit(0); } while(inputStream.hasNextLine()) { String line = inputStream.nextLine(); //read a line of text from the file System.out.println(line); //print the line of text to screen } inputFile.close(); //close the file }

COMP 110: Spring Closing an Input File One you’re finished reading from a text file, you should close the stream Allowing you to write to it later etc This is done using the close method inputFile.close();

COMP 110: Spring Summary: Reading from a File Open the file Create a Scanner object Use try/catch blocks to catch a possible FileNotFoundException Read from the file Use the methods of the Scanner object you created Close the file

COMP 110: Spring The Class File Java provides the class File as a way of representing file names A string such as "out.txt" may be a file name, but Java treats it as any other String object Passing "out.txt" to the constructor of the class file allows us to treat this as a file name in Java

COMP 110: Spring Using the Class File The class File has a constructor that takes in the name of the file Example File outFile = new File("out.txt"); File inFile = new File("in.txt");

COMP 110: Spring Using the Class File The class File also defines several useful methods for working w/ files public boolean canRead() Tests whether the program can read from the file public boolean canWrite() Tests whether the program can write to the file public boolean delete() Attempts to delete the file. Returns true on success public boolean exists() Tests whether the file currently exists public String getName() Returns the name of the file public String getPath() Returns the path name of the file public long length() Returns the length of the file in bytes

COMP 110: Spring Using Path Names When specifying a file name such as "out.txt", the file is assumed to be in the same directory as your program We can refer to a file in a different directory using a path name instead of just the file name Example "C:\\COMP110\\out.txt"

COMP 110: Spring Using Path Names A full path name is a complete path name starting at the root directory e.g. "C:\\COMP110\\out.txt" A relative path name is a path to the file starting at the directory containing your program e.g. "files\\out.txt"

COMP 110: Spring Using Path Names Why use two backslashes (\\) when specifying file paths in Java? e.g. "C:\\COMP110\\out.txt" Recall that backslash is the escape character in Java '\n' – newline, '\t' – tab, etc "\\" in a string means a single backslash

COMP 110: Spring Using File Paths To get around having to use two backslashes, we can use UNIX-style file paths e.g. "C:/COMP110/out.txt" This works on both Windows and UNIX!

COMP 110: Spring File Names What if we don’t know the name of the file when writing the program? Ask the user for the name of the file!

COMP 110: Spring Programming Demo Write a program that searches a file of numbers and displays the largest number, smallest number and average of all numbers in the file Write the statistics out to a separate file Ask the user for the names of the input/output files

COMP 110: Spring Programming Demo Programming

COMP 110: Spring Friday Recitation Short lab Work on Program 5