Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.
-
Upload
gladys-floyd -
Category
Documents
-
view
226 -
download
0
Transcript of Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.
Strings and Text File I/OStrings and Text File I/O(and Exception Handling)(and Exception Handling)
CorrespondsCorresponds
with Chapters 8 and 17with Chapters 8 and 17
The String ClassThe String Class A class in the Java Class LibraryA class in the Java Class Library Part of the Part of the java.langjava.lang package package
NOTE: NOTE: java.langjava.lang is the core package of the basic is the core package of the basic Java classes, including:Java classes, including:
StringString SystemSystem ObjectObject MathMath lots of otherslots of others
Strings are Strings are immutableimmutable (values cannot be (values cannot be changed once created). Another string-like changed once created). Another string-like object that can be changed is object that can be changed is StringBufferStringBuffer..
Initializing a StringInitializing 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 String() is a special method called a constructor, which is
called to create and initialize an object (more about called to create and initialize an object (more about constructors when we do object-oriented programming)constructors when we do object-oriented programming)
This creates a new instance of the String class in the This creates a new instance of the String class in the heapheap
A shortcut way…forget using A shortcut way…forget using newnew:: String s = “the string value”;String s = “the string value”; This does not instantiate a new string. Instead it points to a constant This does not instantiate a new string. Instead it points to a constant
string in the string in the constants poolconstants pool of memory. 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 StringsComparing Strings Suppose you have two string references, Suppose you have two string references, s1s1 and and s2s2.. 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 This tests to see if the variables s1 and s2 are pointing to the same
string object.string object. This is NOT testing to see if the values in two different strings are This is NOT testing to see if the values in two different strings are
identical.identical. To test for equality of value (not equality of reference), you To test for equality of value (not equality of reference), you
use this syntax: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. equalsequals is an instance method of the String class is an instance method of the String class compareTocompareTo is another useful comparison method of the String class. is another useful comparison method of the String class.
See also See also equalsIgnoreCaseequalsIgnoreCase and and compareToIgnoreCasecompareToIgnoreCase
Useful String Instance Useful String Instance MethodsMethods
toUpperCase()toUpperCase() – converts a string to upper case. – converts a string to upper case. Returns a String.Returns a String.
toLowerCase()toLowerCase() – converts a string to lower case. – converts a string to lower case. Returns a String.Returns a String.
substring(int start, int end)substring(int start, int end) – returns the String – returns the String starting a start, ending at end-1. (end is optional).starting a start, ending at end-1. (end is optional).
charAt(int position)charAt(int position) – returns the char value at the – returns the char value at the designated position.designated position.
length()length() – returns the number of characters in the – returns the number of characters in the stringstring
There are lots more useful methods. Check out There are lots more useful methods. Check out the String class in the Java documentation and in the String class in the Java documentation and in chapter 7 of Liang.chapter 7 of Liang.
An Example Using String Methods
HeapFrame Stack
main’sframe
argss1
s2
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
ConstantsPool
Constants pool is a memory location that contains all constants and literals of the application
HeapFrame Stack
main’sframe
argss1
s2
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
ConstantsPool
HeapFrame Stack
main’sframe
argss1
s2
String Object
value a string
String Object
value a string
String Object
value a string
String Object
value another string
ConstantsPool
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’sframe
argss1
s2
String Object
value a string
String Object
value a string
String Object
value a string
String Object
value another string
ConstantsPool
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 LearnedLesson Learned
Don’t expect s1==s2 to work the Don’t expect s1==s2 to work the way you want it to. This will be true way you want it to. This will be true ONLY if the references are pointing ONLY if the references are pointing to the same objectto the same object
To test for equality of VALUE, use To test for equality of VALUE, use s1.equals(s2),s1.equals(s2), or another similar or another similar method.method.
Using other Methods in the Using other Methods in the ExampleExample
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 Using other Methods in the ExampleExample
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 StringTokenizerUsing StringTokenizer
Useful for breaking a string into individual Useful for breaking a string into individual tokens.tokens.
A token is a single unit of the string (a A token is a single unit of the string (a substring).substring).
Tokens are separated by delimitersTokens are separated by delimiters Default delimiters are space, tab (\t), new Default delimiters are space, tab (\t), new
line (\n), and carriage return (\r)line (\n), and carriage return (\r) You can specify your own delimiters if you You can specify your own delimiters if you
wantwant
StringTokenizer ClassStringTokenizer Class
Contained in the Contained in the java.utiljava.util package (need to package (need to importimport this package) 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 StringTokenizer(String str, String delim, boolean
returnDelimiters)returnDelimiters) Important methodsImportant methods
countTokens() – returns the number of tokens in the countTokens() – returns the number of tokens in the stringstring
hasMoreTokens() – returns true or falsehasMoreTokens() – returns true or false nextToken() – returns the next token in the stringnextToken() – 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
output
output
Writing and Reading Text Writing and Reading Text FilesFiles
WritingWriting Create a File instanceCreate a File instance Create a PrintWriter to enable writingCreate a PrintWriter to enable writing Use the PrintWriter class’s print() or println() method to Use the PrintWriter class’s print() or println() method to
write to the filewrite to the file Use the PrintWriter class’s flush() method to force output Use the PrintWriter class’s flush() method to force output
from memory buffer to the filefrom memory buffer to the file Reading:Reading:
Create a File instanceCreate a File instance Create a Scanner instance to enable reading Create a Scanner instance to enable reading Use Scanner’s various methods to readUse Scanner’s various methods to read
hasNext() determines if there is anything more to readhasNext() 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 The FileFile Class Class
Used to internally represent an Used to internally represent an external fileexternal file
Creating an instance of the File will Creating an instance of the File will open the associated file: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 inputScanner – for input PrintWriter – for outputPrintWriter – for output
The The PrintWriterPrintWriter Class Class
Class that supports writing to an Class that supports writing to an output output streamstream
Note: System.out is an output Note: System.out is an output stream, files can also be considered stream, files can also be considered to be streams, and PrintWriter is a to be streams, and PrintWriter is a class for writing to output streamsclass for writing to output streams
What is a STREAM?What is a STREAM?What is a STREAM?What is a STREAM?
A data structure that represents the A data structure that represents the flow of data between RAM and an flow of data between RAM and an external device.external device.
Example:Example: Streams for input and output devices (e.g. Streams for input and output devices (e.g.
keyboard, screen)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
ExceptionsExceptions
In previous examples, the In previous examples, the mainmain method method throwsthrows exceptions. exceptions.
This means the caller of the method This means the caller of the method is responsible for handling the is responsible for handling the exception…not very elegantexception…not very elegant
Instead, it is better if the exceptions Instead, it is better if the exceptions generated are generated are caughtcaught…following …following example shows this.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 HandlingException HandlingException HandlingException Handling
Stream input requires use of Stream input requires use of Exception handlingException handling
standard try/catch format ORstandard try/catch format OR throws IOException in methodsthrows IOException in methods
Exception Handling Using Exception Handling Using trytry and and catchcatch
Exception Handling Using Exception Handling Using trytry and and catchcatch
try{try{
…………....
}}
catch (ExceptionType e){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 Reading Full Lines and Using StringTokenizerUsing StringTokenizer
An alternative to reading one token An alternative to reading one token at a time from the file is to read an at a time from the file is to read an entire line, then use StringTokenizer entire line, then use StringTokenizer to break it up into tokensto break it up into tokens
Using StringTokenizer with Using StringTokenizer with FilesFiles
StrngTokenizer can be used to divide StrngTokenizer can be used to divide the line of text into separate data itemsthe line of text into separate data items
You can use Wrapper classes to convert You can use Wrapper classes to convert strings into numeric data for arithmetic strings into numeric data for arithmetic processingprocessing Integer.parseInt(String)Integer.parseInt(String) – converts a string – converts a string
into an intinto an int Double.parseDouble(String)Double.parseDouble(String) – converts a – converts a
string into a doublestring 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