1 / 48

Strings and Text File I/O (and Exception Handling)

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 Part of the java.lang package NOTE: java.lang is the core package of the basic Java classes, including: String System Object Math

pembroke
Download Presentation

Strings and Text File I/O (and Exception Handling)

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. Strings and Text File I/O(and Exception Handling) Corresponds with Chapters 8 and 17

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

  3. Initializing a String • The formal way: • 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) • This creates a new instance of the String class in the heap • A shortcut way…forget using new: • 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. 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.

  4. Comparing Strings • Suppose you have two string references, s1 and s2. • If you do the following: • if (s1 == s2) • 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. • To test for equality of value (not equality of reference), you use this syntax: • if (s1.equals(s2)) • This will test to see if two different strings have the same value. • equals is an instance method of the String class • compareTo is another useful comparison method of the String class. • See also equalsIgnoreCase and compareToIgnoreCase

  5. Useful String Instance Methods • toUpperCase() – converts a string to upper 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). • charAt(int position) – returns the char value at the designated position. • 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.

  6. An Example Using String Methods

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

  8. String Object String Object String Object String Object a string another string a string a string value value value value args s1 s2 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. main’s frame Constants Pool Frame Stack Heap

  9. String Object String Object String Object String Object another string a string a string a string value value value value args s1 s2 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. main’s frame Constants Pool Frame Stack Heap

  10. String Object String Object String Object String Object another string a string a string a string value value value value args s1 s2 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. main’s frame Constants Pool Frame Stack Heap

  11. 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 • To test for equality of VALUE, use s1.equals(s2), or another similar method.

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

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

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

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

  16. Example from my own notes

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

  18. output

  19. output

  20. output

  21. Writing and Reading Text Files • Writing • Create a File instance • 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 flush() method to force output from memory buffer to the file • Reading: • Create a File instance • Create a Scanner instance to enable reading • Use Scanner’s various methods to read • hasNext() determines if there is anything more to read • Next(), nextDouble(), nextInt(), etc. To use the file i/o examples, put the text files in folder c:\temp

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

  23. The PrintWriter Class • 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

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

  25. Write example from textbook

  26. Read example from textbook hasNext() checks for EOF

  27. 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 • Instead, it is better if the exceptions generated are caught…following example shows this.

  28. Read example from my samples

  29. Input file Output file

  30. Instantiate File and Scanner objects for input

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

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

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

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

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

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

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

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

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

  40. Using StringTokenizer with Files • 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 • Integer.parseInt(String) – converts a string into an int • Double.parseDouble(String) – converts a string into a double

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

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

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

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

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

  46. The parseDouble method converts the string into a number.

  47. Program’s output

More Related