CSC 211 Java I File I/O and more methods. Today’s plan Homework discussion Reading lines from files Writing lines to files All of the above, using methods.

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

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
EXCEPTIONS Def: An exception is a run-time error. Examples include: attempting to divide by zero, or manipulate invalid data.
1 File Output. 2 So far… So far, all of our output has been to System.out  using print(), println(), or printf() All input has been from System.in 
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
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.
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.
CS102--Object Oriented Programming Lecture 14: – File I/O BufferedReader The File class Write to /read from Binary files Copyright © 2008 Xiaoyan Li.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
Lecture 30 Streams and File I/O COMP1681 / SE15 Introduction to Programming.
Week 14 - Monday.  What did we talk about last time?  Image manipulation  Inheritance.
Input/Ouput and Exception Handling. 2 Exceptions  An exception is an object that describes an unusual or erroneous situation  Exceptions are thrown.
Very Brief Introduction to Java I/O with Buffered Reader and Buffered Writer.
Console Input & Output CSS 161: Fundamentals of Computing Joe McCarthy 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.
Computer Programming 2 Lab(1) I.Fatimah Alzahrani.
Winter 2006CISC121 - Prof. McLeod1 Last Time Misc. useful classes in Java: –String –StringTokenizer –Math –System.
File Input/Output. 2Java Programming: From Problem Analysis to Program Design, 3e File Input/Output File: area in secondary storage used to hold information.
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.
CIS Intro to JAVA Lecture Notes Set 6 2-June-05.
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.
Week 14 - Monday.  What did we talk about last time?  Inheritance.
CSI 3125, Preliminaries, page 1 Java I/O. CSI 3125, Preliminaries, page 2 Java I/O Java I/O (Input and Output) is used to process the input and produce.
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.
I/O Basics 26 January Aside from print( ) and println( ), none of the I/O methods have been used significantly. The reason is simple: most real.
File Input & Output Sections Outcomes  Know the difference between files and streams  Use a Scanner to read from a file  add “throws” annotations.
Slides prepared by Rose Williams, Binghamton University Console Input and Output.
Primitive Data Types int is a primitive data type A primitive data type is one that stores only a single piece of data. TypeStorageDescription int 4 bytes+ve.
COMP 110: Spring Announcements Program 5 Milestone 1 was due today Program 4 has been graded.
Chapter 2: Data and Expressions. Variable Declaration In Java when you declare a variable, you must also declare the type of information it will hold.
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.
Lecture 8: I/O Streams types of I/O streams Chaining Streams
CSC 211 Java I for loops and arrays.
Basic Text File Input/Output
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
Building Java Programs
Week 14 - Wednesday CS 121.
I/O Basics.
I/O Streams- Basics Byte Streams and Character Streams
File Input and Output TOPICS File Input Exception Handling File Output.
Exceptions 10-Nov-18.
INPUT STATEMENTS GC 201.
CSS161: Fundamentals of Computing
CSS 161 Fundamentals of Computing Introduction to Computers & Java
Exceptions Exception handling is an important aspect of object-oriented design Chapter 10 focuses on the purpose of exceptions exception messages the.
CSS 161: Fundamentals of Computing
CMSC 202 Exceptions 2nd Lecture.
CMSC 202 Exceptions 2nd Lecture.
Introduction to Computing Using Java
File Handling in Java January 19
Building Java Programs
CMSC 202 Exceptions 2nd Lecture.
CSC1401 Input and Output (with Files)
មជ្ឈមណ្ឌលកូរ៉េ សហ្វវែរ អេច អ ឌី
I/O Exceptions & Working with Files
Exceptions 10-May-19.
LCC 6310 Computation as an Expressive Medium
Chapter 8: Exceptions and I/O Streams
Review for Midterm 3.
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:

CSC 211 Java I File I/O and more methods

Today’s plan Homework discussion Reading lines from files Writing lines to files All of the above, using methods

Questions? OWL exercises Programming assignment

My main method char intent = 'Y'; displayWelcome(); while (intent == 'Y') { rounds++; playRound(smartOrDumb()); intent = playGame(); } displayStatistics();

Today’s plan Homework discussion Reading lines from files Writing lines to files All of the above, using methods

I/O Streams A java stream is an object consisting of a sequence of bytes that flow from a source to a destination Destination Source Stream Source: A program, a file Destination: Can be a file, the console (i.e. output) window….. We read information from an input stream and write information to an output stream

I/O Streams Streams are a bit of an elusive concept in Java -- it can take a while to get used to them  You sort of need to mentally try to picture them over and over again, and the idea of them begins to become clear The java.io.* (input output or I/O for short) package contains many classes that allow us to define various kinds of streams, each with specific characteristicsjava.io.* A program can manage multiple streams at a time The I/O package is quite complex and a detailed analysis of all the classes in this package requires practice and experience

I/O Streams categories There are several categories of I/O streams that you will analyze in depth in CSC 212. Today we will limit ourselves to two I/O streams. The first kind of stream deals with reading information from text files. The second deals with writing information to text files. Here are the classes that we will use for each:  FileReader: To read lines of text from files  PrintWriter: To write lines of text to files

Standard I/O We have already dealt with 3 standard I/O streams  A standard input stream– defined by System.in  A standard output stream – defined by System.out  A standard error stream– defined by System.err Yet we never had to create these streams. This is because these streams are very common and are therefore automatically created for us as soon as we start executing a program

Object review – fields and methods Recall the Triangle, Circle, Square classes from our very first lecture. The Circle class had various fields such as size, color, position. It also had various methods such as changeColor() changeSize() move() In other words, every object of type Circle had properties such as size, color and position. Each object could also “do things” such as change color, change size, move, etc

Object review (brief) contd… In other words, objects are said to have “state” (e.g. the size, color or a circle object) and “behavior” (the various actions that an object can do such as change color). Compare with primitive data types which do not have state or behavior. They simply have one value and that’s it!

Object review (brief) contd… Even our old friends, Strings, are objects. Every string has a state made up of things such as the characters themselves, the length of the string, etc A string also has behaviors such as: length, charAt, equals, etc, etc

I/O streams: been there, done that! System.out  out is a field of the System class.  The data type of ‘out’ is a class called PrintStream You could also say that ‘out’ is an object of type PrintStream  println is a method of the PrintStream class. System.in  in is an object of type InputStream  read is a method that read only raw byte data

Scanner to the rescue Instead of having to deal with the System.in “rawness” we were able to use a Scanner object Scanner console = new Scanner (System.in); And the handy methods like next(), nextInt(), nextDouble() etc. to read from the console Today we will see how to use Scanner to read from a text file

Reading from files Instead of using System.in (i.e. the terminal keyboard) as our input source, we need to create an input source linked to a text file To do this, we need a special stream class, called FileReader The FileReader class has methods that will connect the Scanner class to a specific text file which can then be read

Reading from files The Scanner class has a very convenient method called nextLine() that reads in a line from a text file. So, once we have linked the Scanner class to an input file, we can use the nextLine() method to read in each line of the file The nextLine() method returns a String containing the first line of the file. The method also positions the cursor at the beginning of the next line

public static void main(String[] args) { } while (fileIn.hasNextLine()) { } import java.util.*; import java.io.*; FileReader dataFile = new FileReader("data.txt“); ); Scanner fileIn = new Scanner (dataFile); String aLine = fileIn.nextLine(); System.out.println(aLine); throws FileNotFoundException fileIn.close();

The four steps of file reading 1. Import the necessary packages (java.io.*) 2. Create an input stream to the input source:  FileReader object to the actual file  Scanner associated to the FileReader 3. Use the appropriate methods to read the data: nextLine(), nextInt(), etc. 4. Close the stream: fileIn.close()

Avoiding responsibilities If the program doesn’t find the file or if the file is somehow protected and denies access, the program will throw an exception and abort (crash) Since we don’t know how to handle exception, we “cheat” and delegate responsibility to deal with the exception to someone else

Avoiding responsibilities This is done by adding the following word to the declaration of the method containing the FileReader instantiation throws FileNotFoundException In this example, we add it to the main method Every time you use FileReader you need to either handle or throw the exception or it will not compile You will learn more about exceptions in 212

public static void main(String[] args) { } while (fileIn.hasNextLine()) { } import java.util.*; import java.io.*; FileReader dataFile = new FileReader(“data.txt”); Scanner fileIn = new Scanner ( dataFile); String aLine = fileIn.nextLine(); System.out.println(aLine); throws FileNotFoundException fileIn.close();

The four+ steps of file reading Import the necessary packages (java.io.*) Create an input stream to the input source:  FileReader object to the actual file  Scanner associated to the FileReader Use the appropriate methods to read the data: nextLine(), nextInt(), etc. Close the stream: fileIn.close() Avoid responsibility by throwing an exception to the next level

Exercise Complete Part 1.1 of the lab You will be doing very basic file processing  Open a file  Read a single account number  Close the file

Today’s plan Homework discussion Reading lines from files Writing lines to files All of the above, using methods

Printing to a file We need to create an output stream that is connected to a file For this, we do not use FileReader and Scanner We use the PrintWriter stream class and its methods

public static void main(String[] args) { } import java.util.*; import java.io.*; PrintWriter fileOut = new PrintWriter("data.txt"); String aLine = "A line of text"; fileOut.println(aLine); throws FileNotFoundException fileOut.close();

The four+ steps of file writing Import the necessary packages (java.io.*) Create an output stream to the output source:  PrintWriter object to the actual file Use the appropriate methods to write the data: println(), print(), etc. Close the stream: fileOut.close() Avoid responsibility by throwing an exception to the next level

Important difference What happens when the program attempts to open a file that does not yet exist depends on whether it is for input or output  For input: If the file does not exist, an exception will be thrown and the program will stop  For output: If the file does not exist PrintWriter will create it and not throw an exception Why is this a logical thing to do?

Exercise Complete Parts 1.2 – 1.5 of the lab  Compare the number read from the file with the one entered by the user  Require the user to enter a new account number  Write the new account number to the file you got the first number from You may get stuck at Part 1.4 – that’s ok

Printing to file When PrintWriter writes to an existing file, it overrides whatever is already there, e.g. it does not append So if you do not want to lose what you already have you should: 1. store the existing data in memory, then 2. write the old and the new using PrintWriter

Exercise Complete Part 1.6 of the lab Fix the problem from Part 1.4  Change the program so that it stores the account number already in the file in memory  Then write both account numbers to the file

Today’s plan Reading lines from files Writing lines to files All of the above, using methods

Completing the application We would like to be able to validate a new account number against a long list of account numbers At the same time we want you to get some more practice breaking down the solution into methods

Exercise Complete Parts 2.1 – 2.3 of the lab  Write JEnglish for a program that will check an account number entered by the user against an entire file of account numbers Do not override the work you did in Part 1  You need to open a new BlueJ project, called L8_2 and work on ATM_2.  Both will need to be submitted

My “main” – only 4 lines of code!!! (However each is a method call). int totAcc = getTotalNumOfAccounts(filename); String[] accNums = loadAccounts(totAcc, filename); String newAccNum = getNewAccount(accNums); addAccount(accFileName, numFileName, newAccNum, accNums, totAcc+1);

Exercise Complete Parts 3.1 and 3.2 of the lab Start writing file processing methods  Read how many account numbers we have and load all existing accounts into an array

Exercise Complete Part 3.3 of the lab More methods  Assume that the user input has been validated  Skip ahead to writing to file the new account number and updating the total number of accounts

Final Exam 2 hours and 15 minutes Owl-style questions Open book and notes Heavier emphasis on Arrays and Functions (and functions with arrays!), etc However, is cumulative including today’s lecture While this exam is not meant to be a race against time, if you are having to go to your notes furiously and try to re-figure out how to do everything you WILL run out time. You need to be relatively comfortable with things. For example, if you haven’t practiced file i/o, trying to figure it out in the exam with your notes will cost you a great deal of time.