Using java’s Scanner class To read from input and from a file. (horstmann ch04 and ch 17)

Slides:



Advertisements
Similar presentations
Mr. Wortzman.  So far, we have gotten all our input and written all our output to the console  In reality, this is somewhat uncommon  Instead, we often.
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.
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.
Chapter 11.  Data is often stored in files such as a text file  We need to read that data into our program  Simplest mechanism  Scanner class  First.
1 User Input Create a Scanner object: Scanner inx = new Scanner(System.in); System.out.println("Type a number"); int x = inx.nextInt(); System.out.println("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.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 10 GEORGE KOUTSOGIANNAKIS 1 Copyright: FALL 2014 Illinois Institute of Technology_ George Koutsogiannakis.
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.
Lecture 7 File I/O (and a little bit about exceptions)‏
Evan Korth Scanner class Evan Korth NYU. Evan Korth Java 1.5 (5.0)’s Scanner class Prior to Java 1.5 getting input from the console involved multiple.
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.
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 File Input. 2 Reading Files We have already seen that writing files is (can be?) similar to using System.out Not surprisingly, reading from files is.
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.
Strings as objects Strings are objects. Each String is an instance of the class String They can be constructed thus: String s = new String("Hi mom!");
Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 1 Files.
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 6: File Processing.
Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 1 Files Section 2.13, Section 8.8.
Chapter 16 – Files and Streams. Announcements Only responsible for 16.1,16.3 Only responsible for 16.1,16.3 Other sections “encouraged” Other sections.
Input/Ouput and Exception Handling. 2 Exceptions  An exception is an object that describes an unusual or erroneous situation  Exceptions are thrown.
Two Ways to Store Data in a File Text format Binary format.
Conditional If Week 3. Lecture outcomes Boolean operators – == (equal ) – OR (||) – AND (&&) If statements User input vs command line arguments.
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.
Winter 2006CISC121 - Prof. McLeod1 Last Time Misc. useful classes in Java: –String –StringTokenizer –Math –System.
File I/O (Input and Output). Why use files? Things stored in files are more permanent than things stored in variables in programs. Things stored in files.
1 Recitation 8. 2 Outline Goals of this recitation: 1.Learn about loading files 2.Learn about command line arguments 3.Review of Exceptions.
1 Week 12 l Overview of Streams and File I/O l Text File I/O Streams and File I/O.
Can we talk?. In Hello World we already saw how to do Standard Output. You simply use the command line System.out.println(“text”); There are different.
Miscellaneous topics Chapter 2 Savitch. Miscellaneous topics Standard output using System.out Input using Scanner class.
File IO Basics By Dan Fleck Coming up: Data Streams.
CS101 Lab “File input/Output”. File input, output File : binary file, text file READ/WRITE class of “text file” - File Reading class : FileReader, BufferedReader.
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.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 11 GEORGE KOUTSOGIANNAKIS Copyright: 2015 / Illinois Institute of Technology/George Koutsogiannakis 1.
Week 14 - Monday.  What did we talk about last time?  Inheritance.
Week 12 – Text Files Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
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.
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.
1 / 65 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 12 Programming Fundamentals using Java 1.
Scanner as an iterator Several classes in the Java standard class library Are iterators Actually, the Scanner class is an iterator  The hasNext returns.
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.
Building Java Programs Chapter 6 File Processing Copyright (c) Pearson All rights reserved.
For Friday Finish reading chapter 9 WebCT quiz 17.
File I/O (Input and Output)
Streams & File Input/Output (I/O)
CMSC 202 Text File I/O.
Lesson 8: More File I/O February 5, 2008
Introduction to programming in java
OBJECT ORIENTED PROGRAMMING II LECTURE 2 GEORGE KOUTSOGIANNAKIS
File Input and Output TOPICS File Input Exception Handling File Output.
User Input You’ve seen this: A Scanner object:
Week 14 - Wednesday CS 121.
File Input and Output TOPICS File Input Exception Handling File Output.
CSS161: Fundamentals of Computing
Unit 6 Working with files. Unit 6 Working with files.
OBJECT ORIENTED PROGRAMMING II LECTURE 13_1 GEORGE KOUTSOGIANNAKIS
A Java Application public class Hello { public static void main(String [] args) { System.out.println("Hello, World!"); } } public class.
A Java Application public class Hello { public static void main(String [] args) { System.out.println("Hello, World!"); } } public class.
CSC1401 Input and Output (with Files)
មជ្ឈមណ្ឌលកូរ៉េ សហ្វវែរ អេច អ ឌី
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:

Using java’s Scanner class To read from input and from a file. (horstmann ch04 and ch 17)

Reminder: Scanner objects public Scanner(String x) –Constructs a new scanner object and gives it a String to scan. The newly created object will return words (or other tokens) out of that string. public Scanner(InputStream x) –Constructs a new scanner object and gives it a stream of input to scan. The new object will return words (or other tokens) out of that input stream. public Scanner(File x) –Constructs a new scanner object and gives it a File to scan. The newly created object will return words (or other tokens) out of that File. public String next() –Takes the next string (ending with a space) from x and returns it. public boolean hasNext() –Returns true if there is something left to read from the scanner public int nextInt() –Takes the next thing from stream x, converts it to an int, and returns it. public boolean hasNextInt() –Returns true if there is an int to read from the scanner

Using Scanners to read from files Scanner objects can be used to read from files. We use a java.io.FileReader object to create a stream of input from the file, and then a Scanner object to get strings, ints etc from that stream (“parse” the stream). FileReader readMyFile = new FileReader(“input.txt”); Scanner scanMyFile = new Scanner(readMyFile); String first = scanMyFile.next(); This reads a stream of input from the file, creates a scanner object for that stream, and then every time we call next() for that scanner object, we get the next string from that file. BUT: How do we know if the file exists? What happens if the file we’re trying to read doesn’t exist? If the file we’re trying to read doesn’t exist, an exception will be thrown. Any time we’re reading from a file, we have to catch a possible exception.

Counting the words in a file import java.io.FileReader; import java.util.Scanner; public class testFileScanner{ public static void main(String[] args){ String myFileName = "input.txt"; int wordCount = 0; try{ FileReader myFile = new FileReader(myFileName); Scanner scanMyFile = new Scanner(myFile); while( scanMyFile.hasNext() ) { String currWord = scanMyFile.next(); wordCount = wordCount + 1; } } catch(Exception ex) { System.out.println("exception "+ex.getMessage()+" caught"); } System.out.println("file "+myFileName+ " contains "+wordCount+ " words."); } The FileReader method throws an ioException : we must catch it.

Writing things into a file The object System.out, which we use when printing things to the console, is a member of the PrintWriter class. Objects from this class have methods print(), println() etc. To print things into a file, rather than to the console, we create a new PrintWriter object pointing to that file, and use the print() and println() methods to print things in the file. We ALWAYS have to close an output file when we’re finished putting things in it (using the close() method), otherwise some of what we’ve printed may not end up in the file. ALWAYS!!

Other file actions When we use a FileReader and Scanner to read from a file, it always starts from the beginning of the file. When we use PrintWriter to write to a file, it always starts writing at the beginning of the file, and always overwrites whatever was previously in that file. Java provides ‘random access’ to files, which allows us to write at different locations in the file without overwriting the rest of the file. We won’t look at that, though. Java also allows us to write Objects and other things directly into files: again, we’re not going to look at that either.

Using FileWriter import java.io.PrintWriter; import java.util.Scanner; public class testFileWriter{ public static void main(String[] args){ String myFileName = "output.txt"; try{ PrintWriter myOutFile =new PrintWriter(myFileName); myOutFile.print("hello, my little file, "); myOutFile.println("I will print a line in you!"); myOutFile.close(); } catch(Exception ex) { System.out.println("exception "+ex.getMessage()+" caught"); }