Winter 2006CISC121 - Prof. McLeod1 Last Time Misc. useful classes in Java: –String –StringTokenizer –Math –System.

Slides:



Advertisements
Similar presentations
Lecture 15: I/O and Parsing
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.
CS 206 Introduction to Computer Science II 01 / 20 / 2009 Instructor: Michael Eckmann.
Java Programming Strings Chapter 7.
Today Quiz solutions are posted on the Grading page. Assignment 2 is posted. Due the first Friday after Reading Week. All about null Start File Input/Output.
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.
Introduction to Objects and Input/Output
FIT FIT1002 Computer Programming Unit 19 File I/O and Exceptions.
CS 206 Introduction to Computer Science II 09 / 14 / 2009 Instructor: Michael Eckmann.
CS 206 Introduction to Computer Science II 09 / 09 / 2009 Instructor: Michael Eckmann.
CS 206 Introduction to Computer Science II 01 / 21 / 2009 Instructor: Michael Eckmann.
Chapter 91 Streams and File I/O Chapter 9. 2 Announcements Project 5 due last night Project 6 assigned Exam 2 –Wed., March 21, 7:00 – 8:00 pm, LILY 1105.
CS 206 Introduction to Computer Science II 09 / 04 / 2008 Instructor: Michael Eckmann.
Files and Streams CS 21a Chapter 11 of Horstmann.
COMP 14 Introduction to Programming Miguel A. Otaduy May 17, 2004.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 29, 2005.
Fundamental Programming Structures in Java: Strings.
CS102--Object Oriented Programming Lecture 14: – File I/O BufferedReader The File class Write to /read from Binary files Copyright © 2008 Xiaoyan Li.
CS 206 Introduction to Computer Science II 01 / 23 / 2009 Instructor: Michael Eckmann.
Chapter 12 File Input and Output. Topics Stream Classes Files Text Input and Output JFileChooser for GUI programs Binary files.
Comparing Objects in Java. The == operator When you define an object, for instance Person p = new Person("John", 23); we talk about p as if its value.
Using java’s Scanner class To read from input and from a file. (horstmann ch04 and ch 17)
Week 14 - Monday.  What did we talk about last time?  Image manipulation  Inheritance.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
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.
SE-1020 Dr. Mark L. Hornick 1 File Input and Output.
CS 206 Introduction to Computer Science II 09 / 10 / 2009 Instructor: Michael Eckmann.
Reading External Files By: Greg Patterson APCS 2010.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
Chapter 9-Text File I/O. Overview n Text File I/O and Streams n Writing to a file. n Reading from a file. n Parsing and tokenizing. n Random Access n.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
Fall 2015CISC124 - Prof. McLeod1 CISC124 Have you filled out the lab section survey? (As of last night 54 left to fill out the survey.) TA names have been.
Chapter 7: Characters, Strings, and the StringBuilder.
Lecture 2 Objectives Learn about objects and reference variables.
Odds and Ends. CS 21a 09/18/05 L14: Odds & Ends Slide 2 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights.
CS 206 Introduction to Computer Science II 09 / 11 / 2009 Instructor: Michael Eckmann.
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.
Winter 2006CISC121 - Prof. McLeod1 Last Time Wrapper classes JFileChooser (along with JOptionPane, and JColorChooser !) Text File Output.
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.
Variables and Types Java Part 3. Class Fields  Aka member variable, field variable, instance variable, class variable.  These are the descriptors of.
Chapter 5 Defining Classes II Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
COMP 110: Spring Announcements Program 5 Milestone 1 was due today Program 4 has been graded.
Winter 2006CISC121 - Prof. McLeod1 Stuff We had better discuss a midterm date… –27 Feb. to 3 March or –6 to 10 March.
File Input & Output Sections Outcomes  Know the difference between files and streams  Use a Scanner to read from a file  add “throws” annotations.
Today… Python Keywords. Iteration (or “Loops”!) Winter 2016CISC101 - Prof. McLeod1.
Today… Quiz 1 Topics and “Rules”. Some useful classes from the java.lang package. Includes: –static methods discussion. –The concept of mutability. Winter.
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.
Today Javadoc. Packages and static import. Viewing API source code. Upcoming Topics: –protected access modifier –Using the debugger in Eclipse –JUnit testing.
Winter 2006CISC121 - Prof. McLeod1 Last Time Reviewed class structure: –attributes –methods –(inner classes) Looked at the effects of the modifiers: –public.
Quiz 1 A sample quiz 1 is linked to the grading page on the course web site. Everything up to and including this Friday’s lecture except that conditionals.
Summer 2007CISC121 - Prof. McLeod1 CISC121 – Lecture 3 Last time: –Lots of fundamental Java: Console I/O Conditionals Loops For reading: –File I/O –Exceptions.
Today… StringTokenizer class. Method Overloading. Catching Exceptions (and what they are!). Start Pointers and Aliasing. Winter 2016CMPE212 - Prof. McLeod1.
Last Time Reviewed method overloading. A few useful Java classes:
Programming – Lecture 10 Files, Exception handling (Chapter 12.4)
Streams & File Input/Output (I/O)
Java Programming Lecture 2
Last Time (Midterm Exam!) Before that – methods. Spring 2006
2.5 Another Java Application: Adding Integers
I/O Basics.
Fall 2018 CISC124 12/1/2018 CISC124 Note that the next assignment, on encapsulation, is due next Wednesday at 7pm – not Friday. The next Quiz is not until.
CISC101 Reminders Quiz 2 graded. Assn 2 sample solution is posted.
CISC124 Assignment 3 due tomorrow at 7pm.
Fall 2018 CISC124 2/17/2019 CISC124 Quiz 1 This Week. Topics and format of quiz in last Tuesday’s notes. You are ready for exercises 4 and 5, and assignment.
CISC101 Reminders All assignments are now posted.
CISC101 Reminders Assignment 3 due next Friday. Winter 2019
Winter 2019 CISC101 4/29/2019 CISC101 Reminders
CMPE212 – Reminders Assignment 2 due next Friday.
Presentation transcript:

Winter 2006CISC121 - Prof. McLeod1 Last Time Misc. useful classes in Java: –String –StringTokenizer –Math –System

Winter 2006CISC121 - Prof. McLeod2 Stuff… Assignment 1 is posted (finally!).

Winter 2006CISC121 - Prof. McLeod3 Today Wrapper classes JFileChooser Text File I/O The File class

Winter 2006CISC121 - Prof. McLeod4 Wrapper Classes Sometimes it is necessary for a primitive type value to be an Object, rather than just a primitive type. –Some data structures only store Objects. –Some Java methods only work on Objects. Wrapper classes also contain some useful constants and a few handy methods.

Winter 2006CISC121 - Prof. McLeod5 Wrapper Classes - Cont. Each primitive type has an associated wrapper class: Each wrapper class Object can hold the value that would normally be contained in the primitive type variable, but now has a number of useful static methods. charCharacter intInteger longLong floatFloat doubleDouble

Winter 2006CISC121 - Prof. McLeod6 Integer Wrapper Class - Example Integer number = new Integer(46);//”Wrapping” Integer num = new Integer(“908”); Integer.MAX_VALUE // gives maximum integer Integer.MIN_VALUE // gives minimum integer Integer.parseInt(“453”) // returns 453 Integer.toString(653) // returns “653” number.equals(num) // returns false int aNumber = number.intValue(); // aNumber is 46

Winter 2006CISC121 - Prof. McLeod7 Aside - Why an “ equals ” Method for Objects? The String class also has “ equals ” and “ equalsIgnoreCase ”. These wrapper classes also have an equals method. Why not use the simple boolean comparators ( ==, !=, etc.) with Objects? These comparators just compare memory addresses. How are you going to sort Objects?

Winter 2006CISC121 - Prof. McLeod8 Aside - Why an “ equals ” Method for Objects?, Cont. == can only compare memory addresses when Objects are compared. Most Data Container Objects will have both an equals method and a compareTo method. The equals method tests for equality using whatever you define as “equal”. The compareTo method returns a postive or negative int value (or zero to indicate “equal”), again depending on how you define one Object to be greater or less than another.

Winter 2006CISC121 - Prof. McLeod9 Wrapper Classes – Cont. The Double wrapper class has equivalent methods: Double.MAX_VALUE // gives maximum double value Double.MIN_VALUE // gives minimum double value Double.parseDouble(“0.45E-3”) // returns 0.45E-3 parseDouble is only available in Java 2 and newer versions. See the Java documentation for more on Wrapper classes.

Winter 2006CISC121 - Prof. McLeod10 Character Wrapper Class Many useful methods to work on characters: “ character ” is a char getNumericValue(character) isDigit(character) isLetter(character) isLowerCase(character) isUpperCase(character) toLowerCase(character) toUpperCase(character)

Winter 2006CISC121 - Prof. McLeod11 Built - In GUI Windows We will learn to build our own GUI windows, but you should be aware of the GUI Windows already built into Java: –JOptionPane –JColorChooser –JFileChooser These are all built to perform common tasks and are very easy to use. Imported from the javax.swing package. See “BuiltInDemo.java”.

Winter 2006CISC121 - Prof. McLeod12 JFileChooser A built in file browser/selector dialog box. The demo only used the chooser in the most simple way. For example, you can specify a starting folder and add as many file extension filters as you like. The chooser returns a File object, from which you can obtain much information about the file.

Winter 2006CISC121 - Prof. McLeod13 JFileChooser Window

Winter 2006CISC121 - Prof. McLeod14 JFileChooser Example Code (At the top : –import java.swing.JFileChooser; ) JFileChooser chooser = new JFileChooser(); int result = chooser.showOpenDialog(null); if (result == JFileChooser.APPROVE_OPTION) System.out.println(chooser.getSelectedFile());

Winter 2006CISC121 - Prof. McLeod15 JFileChooser, Cont. Upon completion of the dialog, the getSelectedFile() method returns a File object. This object can easily be used with file I/O code…

Winter 2006CISC121 - Prof. McLeod16 Simple Alternative Prompt the user for a filename as a String, using the console window.

Winter 2006CISC121 - Prof. McLeod17 File I/O Files provide a convenient way to store and re- store to memory larger amounts of data. We will use arrays to store the data in memory, and we’ll talk about these things later. Three kinds of file I/O to discuss: –Text –Binary –Random access For now, we’ll stick with text I/O.

Winter 2006CISC121 - Prof. McLeod18 Text File Output in Java 5.0 Use the PrintWriter class. (As usual), you must import the class: import java.io.PrintWriter; In your program: PrintWriter fileOut = new PrintWriter(outFilename); ( outFilename is a String filename we obtained somewhere else…)

Winter 2006CISC121 - Prof. McLeod19 Text File Output in Java 5.0, Cont. Unfortunately the instantiation of the PrintWriter object can cause a FileNotFoundException to be thrown and you must be ready to catch it: try { writeFile = new PrintWriter(outputFile); } catch (FileNotFoundException e) { System.out.println(e.getMessage()); System.exit(0); } // end try catch

Winter 2006CISC121 - Prof. McLeod20 Aside - File Paths in Strings Sometimes you might have to include a path in the filename, such as “C:\Alan\CISC212\Demo.txt” Don’t forget that if you have to include a “ \ ” in a String, use “ \\ ”, as in: “C:\\Alan\\CISC212\\Demo.txt”

Winter 2006CISC121 - Prof. McLeod21 Text File Output in Java 5.0, Cont. The PrintWriter constructor can also accept a File object (such as provided from JFileChooser !)

Winter 2006CISC121 - Prof. McLeod22 Text File Output in Java 5.0, Cont. The Object fileOut, owns a couple of familiar methods: print() and println(). When you are done writing, don’t forget to close the file with: fileOut.close(); Way easy!!

Winter 2006CISC121 - Prof. McLeod23 Text File Input in Java 5.0 Use the FileReader and Scanner classes. Our usual import statements: import java.util.Scanner; import java.io.FileReader; import java.io.FileNotFoundException; We’ll get to that last one in a minute.

Winter 2006CISC121 - Prof. McLeod24 Text File Input in Java 5.0, Cont. In my program: fileIn = new FileReader("Test.txt"); Scanner fileInput = new Scanner(fileIn); Scanner class’ constructor can also accept a File object directly. Unfortunately the FileReader constructor (what’s a “constructor” anyways?) throws a kind of exception that I cannot ignore - so the code above cannot be used exactly in this way.

Winter 2006CISC121 - Prof. McLeod25 Text File Input in Java 5.0, Cont. This works: FileReader fileIn = null; try{ fileIn = new FileReader("Test.txt"); } catch (FileNotFoundException e) { // Do something clever here! } Scanner fileInput = new Scanner(fileIn);

Winter 2006CISC121 - Prof. McLeod26 Without using FileReader You can also send a File object to the Scanner class when you instantiate it instead of a FileReader object. You will still need to do this in a try catch block as shown in the previous slide. See the demo program “TextFileReaderDemo.java”

Winter 2006CISC121 - Prof. McLeod27 Text File Input in Java 5.0, Cont. We are going to have to talk about try/catch blocks soon! But for now, let’s get back to file input. To get the file contents, and print them to the console, for example: while (fileInput.hasNextLine()) { System.out.println(fileInput.nextLine()); }

Winter 2006CISC121 - Prof. McLeod28 Aside - Scanner Class’ Tokenizer The Scanner class has a built in String Tokenizer. Set the delimiters using the useDelimiter(delimiter_String) method. Obtain the tokens by calling the next() method. The hasNext() method will return false when there are no more tokens.

Winter 2006CISC121 - Prof. McLeod29 File is a class in the java.io.* package. It contains useful utility methods that will help prevent programs crashing from file errors. For example: File myFile = new File(“test.dat”); myFile.exists(); // returns true if file exists myFile.canRead(); // returns true if can read from file myFile.canWrite(); // returns true if can write to file The File Class

Winter 2006CISC121 - Prof. McLeod30 The File Class, Cont. myFile.delete(); // deletes file and returns true if successful myFile.length(); // returns length of file in bytes myFile.getName(); // returns the name of file (like “test.dat”) myFile.getPath(); // returns path of file (like “C:\AlanStuff\JavaSource”)

Winter 2006CISC121 - Prof. McLeod31 Binary and Random Access Binary files contain data exactly as it is stored in memory – you can’t read these files in Notepad! Text file is sequential access only. What does that mean? Random access can access any byte in the file at any time, in any order. More about Binary and Random File Access later!