CS 1312 - PowerPoint PPT Presentation

1 / 56
About This Presentation
Title:

CS 1312

Description:

new line Error! Cannot have. an empty char. Examples using .trim ... Java's JDK 1.02 contained particularly weak IO design. Many classes just didn't work. ... – PowerPoint PPT presentation

Number of Views:32
Avg rating:3.0/5.0
Slides: 57
Provided by: DavidD181
Category:
Tags: testing

less

Transcript and Presenter's Notes

Title: CS 1312


1
CS 1312
  • Introduction to
  • Object Oriented Programming
  • Lecture 10
  • Javas String classJava File I/O

2
class 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
  • pattern matching
  • substring operations
  • conversion of case

3
String concatenation revisited
  • recall concatenation operator
  • bewareSystem.out.println(three plus five is
    3 5)output three plus
    five is 35
  • correctionSystem.out.println(three plus five
    is (3 5))output
    three plus five is 8

4
Other 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)

5
substring 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))

Output asha sh ltblank linegt
6
other 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

7
other 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())

Output 5 2
0 0
0
8
String methods having to do with case
  • .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.

9
.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 Dorfmeister DORFMEISTER DORFMEISTER Dorfme
ister
10
.toLowerCase()
  • String str Paul OakenfoldString strSmall
    str.toLowerCase()System.out.println(str)Syst
    em.out.println(strSmall)System.out.println(str.t
    oLowerCase())System.out.println(str)

Output Paul Oakenfold paul oakenfold paul
oakenfold Paul Oakenfold
11
String comparisons
  • String method .equals()versus
  • String method .equalsIgnoreCase()String str1
    HeLLoString str2 helloSystem.out.println
    ( str1.equals(str2))System.out.println(
    str1.equalsIgnoreCase(str2))

Output false true
12
String comparisons (cont)
  • String method .compareTo(String)
  • UsageString str1, str2. . .if
    (str1.compareTo(str2) lt 0) // str1 is
    alphabetically 1st else if (str1.compareTo(str2)
    0) // str1 equals str2 else // implies
    str1 gt str2
  • // str1 is alphabetically 2nd

13
What? String has a compareTo method??
  • Yes! Hmm.Does that have anything to do with the
    Comparable interface?
  • Yes! Its 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

14
A word about the API(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?
  • Dont be afraid of the APIits your friend!

15
More 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.

16
Examples using.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 ltblank linegt this has two
tabs ltnew linegt
Error!Cannot havean empty char
17
Examples using.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)

.trim() doesnt remove interior whitespace!
Output Stuff this has blanks
18
Finding patterns with .indexOf(String)
catfood 0123456
  • 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))

-1 is returned when the pattern is not found!
Output pattern food begins at 3 pattern dog
begins at -1
19
Finding patterns with . .lastIndexOf(String)
catfood 0123456
  • 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 5 last dog begins at -1
-1 is returned when the pattern is not found!
20
Finding a pattern 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 0 found at 7 found at 12 found
at 19
again, -1 is returned when the pattern is not
found!
21
Testing if a string ends with the given pattern
.endsWith()
  • The method .endsWith(String) returns a boolean
  • String str somebody_at_cc.gatech.edu
  • if (str.endsWith(.edu))
  • System.out.println(
  • str
  • is a school address)
  • else
  • System.out.println(
  • str
  • is not a school address)

Output somebody_at_cc.gatech.edu is a school address
22
Integer.parseInt(String)
  • Integer.parseInt(String) is used to take a
  • String representation and create from it an
  • actual int.

Exceptionthrown!
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 have the
proper form of an int, otherwise it
throws java.lang.NumberFormatExceptionas shown
by the third example above.
23
  • Now on to the next topic
  • File I/O

24
Java 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)

25
Java IO The Big Picture
  • The System.in, System.out, and System.err streams
    are building blocks for more complex IO objects
  • Javas JDK 1.02 contained particularly weak IO
    design. Many classes just didnt 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.)

26
Java IO -- Basic Divisions (1.0)
Java I/O is divided based on directional flow
  • 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

Conceptually, the two are separate
27
Types of InputStreams (1.0)
Javas InputStreams have six general flavors
Watch this class
28
Decorator 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.
29
FilterInputStream Class
  • The FilterInputStream offers a grab bag of
    methods.
  • Sun this is the base class for enhancing input
    stream functionality
  • Eckel they couldnt figure out where else to
    put this stuff, but it seemed like it belonged
    together TIJ (9th ed.)

Avoid it--use InputStreamReader (JDK 1.1)
30
Keyboard Access Use 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

31
Hierarchy of BufferedReader
32
BufferedReader in ActionReading 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()

33
Writing to a File
import java.io. public class DoFileStuff
private PrintWriter outFile public static void
main(String args) try outFile new
PrintWriter( new FileWriter(testout.txt,tr
ue)) outFile.println(this prints to file
) outFile.close() catch (IOException
e) System.out.println(problem with
file) // DoFileStuff
34
Reading from a File
import 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
35
BufferedReader
  • Notice how the BufferedReader created for
    reading from a file is basically the same as the
    one we created for reading from the keyboard!
  • Thats the benefit of using the same decorator
    objectnamely, BufferedReader, to wrap the inner
    object that does differ whether we have
  • input from the keyboard new
    InputStreamReader(System.in)) or
  • input from a file new FileReader(data.txt)
    ))

36
The File Class (1.0)
  • Another important object in Javas 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

37
Using File 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 i0iltlisting.lengthi)
  • System.out.println(listingi)
  • //try
  • catch(Exception bummer)
  • bummer.printStackTrace()
  • //main
  • //class

38
A FilenameFilter Example
  • public 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().toLowerCa
    se()
  • / don't list .java files /
  • return f.indexOf(".class") -1
  • f.indexOf(".java") -1
  • // accept
  • //FilenameFilter
  • ) // anonymous inner class
  • for (int i0 ilt list.length i)
  • System.out.println ("\t"listi)
  • // printDirListing()

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

40
Object 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

41
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

42
Saving 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, dont modify your .java files!

43
Externalization 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

44
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

45
Serialization the transient State
  • 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.

46
Networking Basics
  • This class is not about networking, but in order
    to use the java.net. package and classes, youll
    have to be familiar with some networking
    concepts.
  • The following slides cover simple networking
    terminology.

47
Basic 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)

48
The 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.)

49
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 its
    a point of abstraction that allows for users to
    address a connection between machines.

50
URLs 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

51
Creating an URL
  • The easiest way to create a URL in Java is to
    start with a String
  • try
  • URL myURL new URL (http//www.cc.gatech.edu)
  • // try
  • catch (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 /

52
Using 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.

53
Example URL code
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()
54
Connecting to a URL
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)
55
Extracting the Stream from a URL
  • import 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()

56
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
Write a Comment
User Comments (0)
About PowerShow.com