CS 1312CS 1312
Introduction to
Object Oriented Programming
Lecture 10Java’s String class
Java File I/O
class java.lang.Stringclass java.lang.String• Recall that the type String is provided by the class String!Namely: java.lang.String
• Strings are so common, Java makes some special allowances that make them seem somewhat like primitives.
String str = “Catfood”;String strDitto = new String(“Catfood”);
• Class String has many handy String manipulation methods allowing:1. pattern matching2. substring operations3. conversion of case
String concatenation revisitedString concatenation revisited
• recall concatenation operator +
• beware:System.out.println(“three plus five is “ + 3 + 5);
output: three plus five is 35
• correction:System.out.println(“three plus five is “ + (3 + 5));
output: three plus five is 8
Other String methods revisitedOther String methods revisited
• .length()returns the length of a String
• .charAt( int )returns as a proper char, the single character indexed by int
• .substring( int )returns the substring starting at index int and continuing until the end of the String
• .substring( int1, int2 )returns the substring starting at index int1 (inclusive) and ending at index int2 (exclusive)
substring methods revisitedsubstring methods revisited
Example:String str = “Sasha”;
String strSub = str.substring(1);
System.out.println(strSub);
strSub = str.substring(2,4);
System.out.println(strSub);
System.out.println(str.substring(1,1));
S a s h a0 1 2 3 4
Output:ashash<blank line>
other methods revisitedother methods revisited
Example:String str = “Sasha”;
String strSmall = str.substring(4);
selects “a”
strSmall = str.substring(5);
selects “”
strSmall = str.substring(6);
throws java.lang.StringIndexOutOfBoundsException
strSmall = str.substring(2,1);
throws java.lang.StringIndexOutOfBoundsException
S a s h a0 1 2 3 4
other methods revisitedother methods revisited
Example:String str = “Sasha”;
String emptyOne = new String();
System.out.println(str.length());
System.out.println( str.substring(2,4).length());
System.out.println( str.substring(1,1).length());
System.out.println(“”.length());
System.out.println(emptyOne.length());
S a s h a0 1 2 3 4
Output: 5 2 0 0 0
String methods having to do with String methods having to do with casecase
• .equalsIgnoreCase() can test for equality between two strings while ignoring case
• .toUpperCase() creates an uppercase version of a string
• .toLowerCase() creates a lowercase version of a string
Note: none of these actually modify the original String in any way.
.toUpperCase().toUpperCase()
String str = “Dorfmeister”;
String strBig = str.toUpperCase();
System.out.println(str);
System.out.println(strBig);
System.out.println(str.toUpperCase());
System.out.println(str);
Output:DorfmeisterDORFMEISTERDORFMEISTERDorfmeister
.toLowerCase().toLowerCase() String str = “Paul Oakenfold”;String strSmall = str.toLowerCase();System.out.println(str);System.out.println(strSmall);System.out.println(str.toLowerCase());System.out.println(str);
Output:Paul Oakenfoldpaul oakenfoldpaul oakenfoldPaul Oakenfold
String comparisonsString comparisonsString method .equals()
versus String method .equalsIgnoreCase()
String str1 = “HeLLo”;String str2 = “hello”;System.out.println( str1.equals(str2));System.out.println( str1.equalsIgnoreCase(str2));Output:falsetrue
String comparisons (cont)String comparisons (cont)
String method .compareTo(String)
Usage:String str1, str2;. . .if (str1.compareTo(str2) < 0) { // str1 is alphabetically 1st} else if (str1.compareTo(str2)==0) { // str1 equals str2} else { // implies str1 > str2
// str1 is alphabetically 2nd
}
What? String has a compareTo What? String has a compareTo method??method??
Yes! Hmm….Does that have anything to do with the Comparable interface?
Yes! It’s not just a coincidence!! The class String implements and satisfies the Comparable interface.
Straight from the API:public final class String implements java.io.Serializable, Comparable {
// blah blah…}
A word about the APIA word about the API(application programmer interface)(application programmer interface)
Straight from the API:public final class String implements java.io.Serializable, Comparable {
// blah blah…
}
Notice how that looks exactly like code for a class you might write?
Don’t be afraid of the API…it’s your friend!
More tricks with StringsMore tricks with Strings
• .replace(char, char) replaces all occurrences of the first char with the second char specified
• .trim() removes white space (spaces, newlines, tabs, etc) from both ends of the String
Note: again, none of these actually modify the original String in any way.
Examples usingExamples using.replace(char, char).replace(char, char)
String str = “Carl Cartwright”;String strTwo;strTwo = str.replace(‘C’,‘K’);System.out.println(strTwo);str = “\tthis has two tabs\t”strTwo = str.replace(‘\t’, ‘\n’);System.out.println(strTwo);str = “take out spaces”.replace(‘ ‘, ‘’);Output:Karl Kartwright<blank line>this has two tabs<new line>
Error!Cannot havean empty char
Examples usingExamples using.trim().trim()
String str = “ \n\n\tStuff \n ”;String strTwo;strTwo = str.trim();System.out.println(strTwo);
strTwo = “ this has blanks “.trim();System.out.println(strTwo);
Output:Stuffthis has blanks
.trim() doesn’t remove interior whitespace!
.trim() doesn’t remove interior whitespace!
Finding patterns Finding patterns with .indexOf(String)with .indexOf(String)
String str = “catfood”;int location = str.indexOf(“food”);System.out.println(“pattern food begins at ” + location);
System.out.println(“pattern dog begins at ” +str.indexOf(“dog”));
Output:pattern food begins at 3pattern dog begins at -1
-1 is returned when the pattern is not found!
-1 is returned when the pattern is not found!
catfood0123456
Finding patterns with .Finding patterns with ..lastIndexOf(String).lastIndexOf(String)
String str = “catfood”;int location = str.indexOf(“o”);System.out.println(“last o begins at ” + location);
System.out.println(“last dog begins at ” +str.lastIndexOf(“dog”));
Output:last o begins at 5last dog begins at -1
-1 is returned when the pattern is not found!
-1 is returned when the pattern is not found!
catfood0123456
Finding a pattern Finding a pattern with .indexOf(String, int)with .indexOf(String, int)
Can specify the starting index for the pattern search.Useful if we want to find ALL occurrences!
String str = “abracadabra abracadabra”;int index = str.indexOf(“abra”);while (index != -1) { System.out.println( “found at “ + index); index = str.indexOf(“abra”, index + 1);} // note the final –1 is not printed
Output:found at 0found at 7found at 12found at 19
again, -1 is returned when the pattern is not found!
again, -1 is returned when the pattern is not found!
Testing if a string ends with the given Testing if a string ends with the given patternpattern .endsWith() .endsWith()
The method .endsWith(String) returns a boolean
String str = “[email protected]”;if (str.endsWith(“.edu”)) System.out.println( str + “ is a school address”);else System.out.println( str + “ is not a school address”);
Output:[email protected] is a school address
Integer.parseInt(String)Integer.parseInt(String)
Integer.parseInt(String) is used to take a
String representation and create from it an
actual int.
String str = “125”;int j = Integer.parseInt(str);int k = Integer.parserInt(“-1020”);int wrong = Integer.parserInt(“-1020.55”);
In each case, the String must actually havethe proper form of an int, otherwise it throwsjava.lang.NumberFormatExceptionas shown by the third example above.
Exceptionthrown!
Now on to the next topic:Now on to the next topic:
File I/OFile I/O
Java I/O: Fun with StreamsJava I/O: Fun with Streams
• In general, there are streams inherent in any Java process:– System.in– System.out– System.err
• You are already familiar with most of these streams. E.g.,– System.out.println (“This is the out stream”);
Java IO: The Big PictureJava IO: The Big Picture• The System.in, System.out, and System.err streams are building blocks for more complex IO objects
• Java’s JDK 1.02 contained particularly weak IO design. Many classes just didn’t work.
• Instead of scrapping JDK 1.02, the Sun engineers extended the 1.02 library with JDK 1.1
• In general, the JDK 1.1 classes provide adequate IO. (In some instances, one still must use JDK 1.02.)
Java IO -- Basic Divisions (1.0)Java IO -- Basic Divisions (1.0)
• InputStream:– through
inheritance, all derivatives of InputStream have the basic method “read()” to access a byte or an array of bytes
• OutputStream– through
inheritance, all derivatives of OutputStream have the basic method “write()” to write a single byte
Java I/O is divided based on directional flow:
Conceptually, the two are separateConceptually, the two are separate
Types of InputStreams (1.0)Types of InputStreams (1.0)
Class ByteAr-rayIn-put-Stream
String-Buffer-Input-Stream
FileInputStream
PipedIn-put-Stream
SequenceInput-Stream
FilterIn-put-Stream
Purpose Creates amemorybuffer foruse as anInputStream
Makes aString intoanInputStream
Readingfrom a fileon disk
Catch datafrom anassociatedPipedOutputStream
Converts twoor moreInputStreamsinto a singleinpustream
Abstractclass usefulfordecorators
Use Data SourceHook this upto aFilterInputStream forinterface
Consuctedwith aString, butunderlyingclassmethods useStringBuffer
String of filename, or aFile object orFileDescriptor object tocreate
Multi-threadinguses mainly;useFilterInputStreaminterfaces
Pass in twoInputStreamobject, or useanEnumerationofInputStreamobjects
(next slide)
Java’s InputStreams have six general flavors:
Decorator ClassesDecorator Classes• Java IO uses ‘decorator’ objects to
provide layers of functionality to IO classes
Concept: A ‘decorator pattern’ wraps the inner object, all using the same interface devices.
Pro/Con: Flexibility with the cost of complexity
Example: notice how many IO classes feature the “readLine()” method.
FilterInputStream FilterInputStream ClassClass
• The FilterInputStream offers a ‘grab The FilterInputStream offers a ‘grab bag’ of methods.bag’ of methods.– Sun: this is the base class for “enhancing Sun: this is the base class for “enhancing
input stream functionality”input stream functionality”– Eckel: “[they] couldn’t figure out where else Eckel: “[they] couldn’t figure out where else
to put this stuff, but it seemed like it to put this stuff, but it seemed like it belonged together” TIJ (9th ed.)belonged together” TIJ (9th ed.)
Avoid it--use InputStreamReader (JDK 1.1)
Keyboard Access: Use Keyboard Access: Use InputStreamReader (1.1)InputStreamReader (1.1)
• For reading keystrokes, use an InputStreamReader
• Wrap with a BufferedReader decorator:
public IOHelper(boolean DEBUG) { this.DEBUG = DEBUG; /* For reading data from standard in (stdin)*/ iStreamReader = new InputStreamReader(System.in); keyboard = new BufferedReader(iStreamReader); } // constructor
Hierarchy of BufferedReaderHierarchy of BufferedReader
BufferedReader in ActionBufferedReader in ActionReading from the KeyboardReading from the Keyboard
public String readLine() { String strInput =""; try { strInput = keyboard.readLine(); } catch (Exception e) { System.err.println (”Keyboard error:\n\t" + e.toString()); e.printStackTrace(); System.exit(0); } return strInput;} // readLine()
Writing to a FileWriting to a Fileimport java.io.*;public class DoFileStuff { private PrintWriter outFile;public static void main(String[] args) { try { outFile = new PrintWriter( new FileWriter(“testout.txt”,true)); outFile.println(“this prints to file ”); outFile.close(); } catch (IOException e) { System.out.println(“problem with file”); }} // DoFileStuff
Reading from a FileReading from a Fileimport java.io.*;public class DoFileStuff { private BufferedReader inFile;public static void main(String[] args) { String line; try { inFile = new BufferedReader( new FileReader(“data.txt”)); while((line = inFile.readLine()) != null){ System.out.println(line); } // end while inFile.close(); } // end try catch (IOException e) { System.out.println(“problem with file”); } // end catch} // end class DoFileStuff
BufferedReaderBufferedReader• Notice how the BufferedReader created for reading
from a file is basically the same as the one we created for reading from the keyboard!
• That’s the benefit of using the same decorator objectnamely, BufferedReader, to wrap the inner object that does differ whether we have
1. input from the keyboard new InputStreamReader(System.in)) or
2. input from a file new FileReader(“data.txt”)))
The The FileFile Class (1.0) Class (1.0)
• Another important object in Java’s IO library is the File Class
• Misnomer: the File class does not necessarily refer to a single file. It can represent the name of a single file, or the names of a set of files.
• The method list() returns a String[] array of file names
• Therefore, ‘filepath’ might have been a better name
• There is no JDK 1.1 equivalent
Using Using FileFile to Obtain A Directory Listing to Obtain A Directory Listing
public class Lister {
public static void main (String args[]){
try{
File path = new File (“.”);
String[] listing = path.list();
for(int i=0;i<=listing.length;i++)
System.out.println(listing[i]);
} //try
catch(Exception bummer) {
bummer.printStackTrace();
}
} //main
} //class
A FilenameFilter ExampleA FilenameFilter Examplepublic void printDirListing(){
final String[] list; /* MUST be final */
final File path = new File("."); /* MUST be final */
list = path.list( new FilenameFilter(){
public boolean accept (File dir, String n){
String f = new File(n).getName().toLowerCase();
/* don't list .java files */
return f.indexOf(".class") == -1
&& f.indexOf(".java") == -1;
} // accept
} //FilenameFilter
); // anonymous inner class
for (int i=0; i< list.length; i++)
System.out.println ("\t"+list[i]);
} // printDirListing()
Object Serialization--eh?Object Serialization--eh?
• Normally, objects live only during the life of the program. Stop the program, and the object disappears
• JDK 1.1 offers the Serializable interface to create ‘lightweight persistence’.
• Persistent objects live beyond the life of the program, usually in byte form on disk or on a network.
Object SerializationObject Serialization• You may have heard about ‘object
persistence’ as a new Java buzzword.• The Serializable interface provides this
capability for lightweight persistence.• The Serializable interface is lightweight
because one must manually create/load persistent objects.
• This technique is necessary for remote method invocation (RMI), where objects live on another machine
Object Serialization (cont)Object Serialization (cont)
• Serialization is also necessary for Java Bean design, where functional components have state information created and saved during design, not runtime.
• How does one serialize an object? Just have your class implement the Serializable interface and save appropriately
Saving Serialized ObjectsSaving Serialized Objects
• Simple: create an OutputStream, and wrap it with an ObjectOutputStream.
• Twin methods:– writeObject();– readObject();
/* requires InputStream wrapped by ObjectInputStream */
• Restoring objects requires a .class file!– Therefore, don’t modify your .java files!
Externalization of ObjectsExternalization of Objects• JDK 1.1 also has the java.io.Externalizable class.• Externalization is different from serialization.• The Externalizable interface extends Serializable and adds two methods one must implement:
public abstract void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
public abstract void writeExternal(ObjectOutput out) throws IOException
Externalized Objects (cont)Externalized Objects (cont)• Externalized Objects are similar to serialized
objects, except that the objects themselves control the field creation during reading and writing.
• The readExternal and writeExternal are called with readObject() and writeObject()
• This produces greater security, and offers the possibility of selective serialization
• Note Bene: Constructors for externalized objects must be public
Serialization & the Serialization & the transienttransient StateState
• There may be a time when we want to serialize an object, but omit certain key features, like passwords or other sensitive data.
• Even objects and data identified as private get serialized. How does one keep data out of externalized objects?
• Solution: use the transient keyword:private transient String password = “pssst.”;
• Data and methods identified as transient are not serialized.
Networking BasicsNetworking Basics
• This class is not about networking, but in order to use the java.net.* package and classes, you’ll have to be familiar with some networking concepts.
• The following slides cover simple networking terminology.
Basic Client-Server RelationsBasic Client-Server Relations• At a fundamental level, all networked applications divide into
either client or server services. Client and server applications communicate with each other through some type of communications link--often an agreed protocol for sharing information.
• It is often helpful to conceive of the network as a series of ‘layers’, representing different levels of abstraction.
• At the top level, we have applications--web browsers, ftp programs, telnet applications.
• This top-level software utilizes a ‘transport layer’ (TCP protocol)
• Which in turn uses a network layer (IP protocol: e.g., IPv4)
• Which in turn uses a link layer (ethernet protocol)
Application
Transport
Network
Link
User Process
Protocol stack in kernel
The User-Process LevelThe User-Process Level• For the most part, we will be utilizing the user-
process level, and rely on TCP/IP protocols.
• Defined: The Transport Control Protocol (TCP) is a connection-based protocol that provides reliable flow of data between two computers.
• If time permits, we may take a look at UDP (user datagram protocol) communications as well. (In short: UDP has no guarantees that information will arrive, but it is considerably faster.)
Ports & Sockets: What?Ports & Sockets: What?• Generally, computers possess only a single physical
connection to a network. All information arrives and departs through this connection. For many different applications to use this same connection, computers create logical groupings, or ports.
• Together with an IP address--a unique number assigned to a machine on a network--a port allows one to identify a specific process on a specific machine.
• A socket is a software abstraction that provides a terminus to a connection between machines; it’s a point of abstraction that allows for users to address a connection between machines.
URLs: How ToURLs: How To
An essential part of any socket is the URL. A URL has two main components:
Other components include:
Host Name -- the name of the machine ‘hosting’ the resource
Filename -- the pathname to the file on the host
Port Number -- the port number to which to connect (typically optional).
Reference -- a reference to a named anchor within a resource that usually identifies a specific location within a file (typically optional).
URL = uniform resource locator
Creating an URLCreating an URLThe easiest way to create a URL in Java is to start with a String: try {
URL myURL = new URL (“http://www.cc.gatech.edu”);} // trycatch (MalformedURLException e) { System.err.println (“This method: “ +
e.toString());} // catch
URLs can also be created relative to an existing URL:try {URL firstURL = new URL(
“http://www.foo.com/top_level”); URL secondURL = new URL( firstURL, “lower_level”);}catch (Exception e){/* maybe do nothing */;}
Using a URLUsing a URL
URLs contain many useful methods, including:
getProtocol() returns the protocol identifier component of the URL (ftp/http, e.g.).
getHost() returns the host name component of the URL.
getPort() returns the port number component of the URL (or -1 if not set).
getFile() returns the filename component of the URL.
getRef() returns the reference component of the URL.
import java.net.*;import java.io.*;
public class URLReader { public static void main( String[] args) throws Exception { URL myURL = new URL("http://www.blarg.foo.org/"); BufferedReader in =
new BufferedReader(new InputStreamReader (myURL.openStream()));
String strInput;
while ((strInput = in.readLine()) != null) System.out.println(strInput); in.close(); }}
Example URL code
One can also use “openConnection()” to connect to a URL. This creates a communication link between your Java program and the URL over the network. For example:
try { URL myURL = new URL("http://www.blarg.foo.org/");
myURL.openConnection(); } catch (MalformedURLException e) {;} catch (IOException e) {;}
Connecting to a URL
Extracting the Stream from a URLExtracting the Stream from a URLimport java.net.*; import java.io.*;public class URLConnectionReader { public static void main
(String[] args) throws Exception { URL myURL = new URL("http://www.cc.gatech.edu/"); URLConnection uc = myURL .openConnection(); BufferedReader in = new BufferedReader
(new InputStreamReader(uc.getInputStream()));
/* see getOutputStream() */ String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); } }
BufferedReader strikes again!BufferedReader strikes again!
• What do you know, even a URL can be used to create our old familiar input device, the BufferedReader
• Makes reading from a URL over the internet almost as trivial as reading from a file or the keyboard!
• Having the same interface is very handy
Top Related