1 / 38

CSC 211 Java I

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') {

padillat
Download Presentation

CSC 211 Java I

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. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CSC 211 Java I File I/O and more methods

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

  3. Questions? OWL exercises Programming assignment

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

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

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

  7. 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 characteristics • 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

  8. 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

  9. 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

  10. 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

  11. 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!

  12. 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

  13. 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 PrintStreamclass. • System.in • in is an object of type InputStream • readis a method that read only raw byte data

  14. Scanner to the rescue • Instead of having to deal with the System.in “rawness” we were able to use a Scanner object Scannerconsole = 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

  15. 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

  16. 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

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

  18. 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()

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

  20. 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

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

  22. 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

  23. 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

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

  25. 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

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

  27. 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

  28. 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?

  29. 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

  30. 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: • store the existing data in memory, then • write the old and the new using PrintWriter

  31. 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

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

  33. 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

  34. 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

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

  36. 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

  37. 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

  38. 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.

More Related