Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.

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.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 9 Strings.
Chapter 7 Strings F To process strings using the String class, the StringBuffer class, and the StringTokenizer class. F To use the String class to process.
1 Strings and Text I/O. 2 Motivations Often you encounter the problems that involve string processing and file input and output. Suppose you need to write.
Chapter 7 Strings F Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. F Use the String class to process.
Java Programming Strings Chapter 7.
Strings An extension of types A class that encompasses a character array and provides many useful behaviors Chapter 9 Strings are IMMUTABLE.
©2004 Brooks/Cole Chapter 7 Strings and Characters.
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.
Introduction to Objects and Input/Output
Chapter 9 Characters and Strings. Topics Character primitives Character Wrapper class More String Methods String Comparison String Buffer String Tokenizer.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 9 Characters and Strings (sections ,
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.
23-Jun-15 Strings, Etc. Part I: String s. 2 About Strings There is a special syntax for constructing strings: "Hello" Strings, unlike most other objects,
StringBuffer class  Alternative to String class  Can be used wherever a string is used  More flexible than String  Has three constructors and more.
Fundamental Programming Structures in Java: Strings.
1 StringTokenizer and StringBuffer classes Overview l StringTokenizer class l Some StringTokenizer methods l StringTokenizer examples l StringBuffer class.
Strings, Etc. Part I: Strings. About Strings There is a special syntax for constructing strings: "Hello" Strings, unlike most other objects, have a defined.
1 Fall 2008ACS-1903 for Loop Reading files String conversions Random class.
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Odds and Ends Strings (from Chapter 9) StringTokenizer.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 9 Characters and Strings (sections ,
Slides prepared by Rose Williams, Binghamton University Chapter 10 File I/O.
COMP 110 Introduction to Programming Mr. Joshua Stough September 10, 2007.
1 Infinite Loops  The body of a while loop eventually must make the condition false  If not, it is an infinite loop, which will execute until the user.
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.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Session 5 java.lang package Using array java.io package: StringTokenizer, ArrayList, Vector Using Generic.
1 Course Lectures Available on line:
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 7 Strings.
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.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 3 Introduction to Objects and Input/Output.
Chapter 7 Strings  Use the String class to process fixed strings.  Use the StringBuffer class to process flexible strings.  Use the StringTokenizer.
Chapter 7 Strings F Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. F Use the String class to process.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
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.
An Introduction to Java Programming and Object-Oriented Application Development Chapter 7 Characters, Strings, and Formatting.
Objectives ► Become familiar with the class String ► ► Learn how to use input and output dialog boxes in a program ► ► Learn how to tokenize the input.
Lecture 2 Objectives Learn about objects and reference variables.
Strings Chapter 7 CSCI CSCI 1302 – Strings2 Outline Introduction The String class –Constructing a String –Immutable and Canonical Strings –String.
Jaeki Song JAVA Lecture 07 String. Jaeki Song JAVA Outline String class String comparisons String conversions StringBuffer class StringTokenizer class.
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.
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.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 3 Introduction to Objects and Input/Output.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1.
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.
File Input and Output Appendix E © 2015 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Slides prepared by Rose Williams, Binghamton University Console Input and Output.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Scanner Review Java Foundations: Introduction to Programming and Data Structures.
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.
Strings.
OBJECT ORIENTED PROGRAMMING II LECTURE 2 GEORGE KOUTSOGIANNAKIS
I/O Basics.
MSIS 655 Advanced Business Applications Programming
Streams and File I/O Chapter 14.
CHAPTER 5 (PART 2) JAVA FILE INPUT/OUTPUT
OBJECT ORIENTED PROGRAMMING II LECTURE 13_1 GEORGE KOUTSOGIANNAKIS
Lecture 07 String Jaeki Song.
OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS
Chapter 7 Strings Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. Use the String class to process fixed.
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:

Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17

The String Class A class in the Java Class Library A class in the Java Class Library Part of the java.lang package Part of the java.lang package NOTE: java.lang is the core package of the basic Java classes, including: NOTE: java.lang is the core package of the basic Java classes, including: String String System System Object Object Math Math lots of others lots of others Strings are immutable (values cannot be changed once created). Another string-like object that can be changed is StringBuffer. Strings are immutable (values cannot be changed once created). Another string-like object that can be changed is StringBuffer.

Initializing a String The formal way: The formal way: String s = new String(“the string value”); String s = new String(“the string value”); String() is a special method called a constructor, which is called to create and initialize an object (more about constructors when we do object-oriented programming) String() is a special method called a constructor, which is called to create and initialize an object (more about constructors when we do object-oriented programming) This creates a new instance of the String class in the heap This creates a new instance of the String class in the heap A shortcut way…forget using new: A shortcut way…forget using new: String s = “the string value”; String s = “the string value”; This does not instantiate a new string. Instead it points to a constant string in the constants pool of memory. This does not instantiate a new string. Instead it points to a constant string in the constants pool of memory. NOTE: like with any other object instantiation, the variable s is NOT a String object. It is a REFERENCE to a String object. The String object itself is on the heap. s points at it.

Comparing Strings Suppose you have two string references, s1 and s2. Suppose you have two string references, s1 and s2. If you do the following: If you do the following: if (s1 == s2) if (s1 == s2) This tests to see if the variables s1 and s2 are pointing to the same string object. This tests to see if the variables s1 and s2 are pointing to the same string object. This is NOT testing to see if the values in two different strings are identical. This is NOT testing to see if the values in two different strings are identical. To test for equality of value (not equality of reference), you use this syntax: To test for equality of value (not equality of reference), you use this syntax: if (s1.equals(s2)) if (s1.equals(s2)) This will test to see if two different strings have the same value. This will test to see if two different strings have the same value. equals is an instance method of the String class equals is an instance method of the String class compareTo is another useful comparison method of the String class. compareTo is another useful comparison method of the String class. See also equalsIgnoreCase and compareToIgnoreCase See also equalsIgnoreCase and compareToIgnoreCase

Useful String Instance Methods toUpperCase() – converts a string to upper case. Returns a String. toUpperCase() – converts a string to upper case. Returns a String. toLowerCase() – converts a string to lower case. Returns a String. toLowerCase() – converts a string to lower case. Returns a String. substring(int start, int end) – returns the String starting a start, ending at end-1. (end is optional). substring(int start, int end) – returns the String starting a start, ending at end-1. (end is optional). charAt(int position) – returns the char value at the designated position. charAt(int position) – returns the char value at the designated position. length() – returns the number of characters in the string length() – returns the number of characters in the string There are lots more useful methods. Check out the String class in the Java documentation and in chapter 7 of Liang. There are lots more useful methods. Check out the String class in the Java documentation and in chapter 7 of Liang.

An Example Using String Methods

HeapFrame Stack main’s frame args s1s2 s1 and s2 are equal. They point to the same object, which is a literal string located in the constants pool. String Object value a string String Object value another string Constants Pool Constants pool is a memory location that contains all constants and literals of the application

HeapFrame Stack main’s frame args s1s2 String Object value a string String Object value a string s1 and s2 are NOT equal. They point to different objects. But, the contents of the strings pointed at by s1 and s2 are equal. String Object value a string String Object value another string Constants Pool

HeapFrame Stack main’s frame args s1s2 String Object value a string String Object value a string String Object value a string String Object value another string Constants Pool S2 is changed to point to the other literal string in the constants pool. The value of the old string pointed at by s2 does not change. Eventually, this string will be discarded by the garbage collector.

HeapFrame Stack main’s frame args s1s2 String Object value a string String Object value a string String Object value a string String Object value another string Constants Pool S1 is changed to point to the same string that s2 points at. The value of the old string pointed at by s1 does not change. Eventually, this string will be discarded by the garbage collector.

Lesson Learned Don’t expect s1==s2 to work the way you want it to. This will be true ONLY if the references are pointing to the same object Don’t expect s1==s2 to work the way you want it to. This will be true ONLY if the references are pointing to the same object To test for equality of VALUE, use s1.equals(s2), or another similar method. To test for equality of VALUE, use s1.equals(s2), or another similar method.

Using other Methods in the Example Instance method toUpperCase called with respect to the string object pointed at by s1. toUpperCase creates a new String object and returns a reference to that new object, which contains the same value as the string of s1, but entirely in upper case. Instance method substring called with respect to the string object pointed at by s1. substring creates a new String object and returns a reference to that new object, which contains the characters from position 3 to position 5 of the string pointed at by s1.

Using other Methods in the Example substring returns a reference to a new String object toUpperCase called with respect to the String object returned from substring NOTE: cascading method calls

Using StringTokenizer Useful for breaking a string into individual tokens. Useful for breaking a string into individual tokens. A token is a single unit of the string (a substring). A token is a single unit of the string (a substring). Tokens are separated by delimiters Tokens are separated by delimiters Default delimiters are space, tab (\t), new line (\n), and carriage return (\r) Default delimiters are space, tab (\t), new line (\n), and carriage return (\r) You can specify your own delimiters if you want You can specify your own delimiters if you want

StringTokenizer Class Contained in the java.util package (need to import this package) Contained in the java.util package (need to import this package) Constructors: Constructors: StringTokenizer(String str) StringTokenizer(String str) StringTokenizer(String str, String delim) StringTokenizer(String str, String delim) StringTokenizer(String str, String delim, boolean returnDelimiters) StringTokenizer(String str, String delim, boolean returnDelimiters) Important methods Important methods countTokens() – returns the number of tokens in the string countTokens() – returns the number of tokens in the string hasMoreTokens() – returns true or false hasMoreTokens() – returns true or false nextToken() – returns the next token in the string nextToken() – returns the next token in the string Note: a constructor is a method that is invoked when an object is instantiated (created)

Example from my own notes

Import the package Instantiate the tokenizer object Find out how many tokens there are Get each token Instantiate the tokenizer object with special delimiters Instantiate the tokenizer object with special delimiters, here the delimters are tokens

output

Writing and Reading Text Files Writing Writing Create a File instance Create a File instance Create a PrintWriter to enable writing Create a PrintWriter to enable writing Use the PrintWriter class’s print() or println() method to write to the file Use the PrintWriter class’s print() or println() method to write to the file Use the PrintWriter class’s flush() method to force output from memory buffer to the file Use the PrintWriter class’s flush() method to force output from memory buffer to the file Reading: Reading: Create a File instance Create a File instance Create a Scanner instance to enable reading Create a Scanner instance to enable reading Use Scanner’s various methods to read Use Scanner’s various methods to read hasNext() determines if there is anything more to read hasNext() determines if there is anything more to read Next(), nextDouble(), nextInt(), etc. Next(), nextDouble(), nextInt(), etc. To use the file i/o examples, put the text files in folder c:\temp

The File Class Used to internally represent an external file Used to internally represent an external file Creating an instance of the File will open the associated file: Creating an instance of the File will open the associated file: File myfile = new File(“filename”); File myfile = new File(“filename”); Files can then be used by: Files can then be used by: Scanner – for input Scanner – for input PrintWriter – for output PrintWriter – for output

The PrintWriter Class Class that supports writing to an output stream Class that supports writing to an output stream Note: System.out is an output stream, files can also be considered to be streams, and PrintWriter is a class for writing to output streams Note: System.out is an output stream, files can also be considered to be streams, and PrintWriter is a class for writing to output streams

What is a STREAM? A data structure that represents the flow of data between RAM and an external device. A data structure that represents the flow of data between RAM and an external device. Example: Example: Streams for input and output devices (e.g. keyboard, screen) Streams for input and output devices (e.g. keyboard, screen) Streams for data files (on disk) Streams for data files (on disk) Streams for sockets (network connections) Streams for sockets (network connections)

Write example from textbook

Read example from textbook hasNext() checks for EOF

Exceptions In previous examples, the main method throws exceptions. In previous examples, the main method throws exceptions. This means the caller of the method is responsible for handling the exception…not very elegant This means the caller of the method is responsible for handling the exception…not very elegant Instead, it is better if the exceptions generated are caught…following example shows this. Instead, it is better if the exceptions generated are caught…following example shows this.

Read example from my samples

Input file Output file

Instantiate File and Scanner objects for input

Read/Write example from my samples Instantiate File and PrintWriter objects for output

Here I use an outer loop to check for EOF, and to read the label and initialize the tot for summing Read/Write example from my samples

I use the inner loop to to read all the numbers from the line and sum them together. Note that hasNextDouble() checks to see if the next token is a number. Read/Write example from my samples

Note that the same methods print() and println() can be used for System.out (the standard output display stream) and for the PrintWriter for file output. Read/Write example from my samples

Make sure to close the output file after done writing…this forces any data remaining in the memory buffer to be written to the file Read/Write example from my samples

Exception Handling Stream input requires use of Exception handling Stream input requires use of Exception handling standard try/catch format OR standard try/catch format OR throws IOException in methods throws IOException in methods

Exception Handling Using try and catch try{……..} catch (ExceptionType e){ ……..} If code within the try block causes an error, the program will automatically branch to the catch block

Read/Write example from my samples Any code that could cause an exception should be placed in the try portion. If an exception occurs, the program will immediately branch to the catch section The Exception’s toString() method gives the specific error message.

Reading Full Lines and Using StringTokenizer An alternative to reading one token at a time from the file is to read an entire line, then use StringTokenizer to break it up into tokens An alternative to reading one token at a time from the file is to read an entire line, then use StringTokenizer to break it up into tokens

Using StringTokenizer with Files StrngTokenizer can be used to divide the line of text into separate data items StrngTokenizer can be used to divide the line of text into separate data items You can use Wrapper classes to convert strings into numeric data for arithmetic processing You can use Wrapper classes to convert strings into numeric data for arithmetic processing Integer.parseInt(String) – converts a string into an int Integer.parseInt(String) – converts a string into an int Double.parseDouble(String) – converts a string into a double Double.parseDouble(String) – converts a string into a double

To use StringTokenizer, you must import the java.util package, and for File you need java.io.

To create a string tokenizer, call the StringTokenizer constructor, passing the string to tokenize as an argument.

The hasMoreTokens method returns true or false, depending on if there are more tokens in the string.

The nextToken method returns a string, which is the next token in the source string.

Here, I am checking to see if the character of the token is a number (a digit).

The parseDouble method converts the string into a number.

Program’s output