Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 1312 Introduction to Object Oriented Programming Lecture 10 Java’s String class Java File I/O.

Similar presentations


Presentation on theme: "CS 1312 Introduction to Object Oriented Programming Lecture 10 Java’s String class Java File I/O."— Presentation transcript:

1

2 CS 1312 Introduction to Object Oriented Programming Lecture 10 Java’s String class Java File I/O

3 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: 1. pattern matching 2.substring operations 3.conversion of case

4 String 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

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

6 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)); Sasha 01234 Output: asha sh

7 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 Sasha 01234

8 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()); Sasha 01234 Output: 5 2 0

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

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

11 .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 Oakenfold paul oakenfold Paul Oakenfold

12 String comparisons String 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: false true

13 String comparisons (cont) String method.compareTo(String) Usage: String str1, str2;... if (str1.compareTo(str2) str2 // str1 is alphabetically 2 nd }

14 What? String has a compareTo 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… }

15 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? Don’t be afraid of the API…it’s your friend!

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

17 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 this has two tabs Error! Cannot have an empty char

18 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); Output: Stuff this has blanks.trim() doesn’t remove interior whitespace!

19 Finding patterns 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 3 pattern dog begins at -1 -1 is returned when the pattern is not found! catfood 0123456

20 Finding patterns with..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 5 last dog begins at -1 -1 is returned when the pattern is not found! catfood 0123456

21 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!

22 Testing if a string ends with the given pattern.endsWith() The method.endsWith(String) returns a boolean String str = “somebody@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@cc.gatech.edu is a school address

23 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 have the proper form of an int, otherwise it throws java.lang.NumberFormatException as shown by the third example above. Exception thrown!

24 Now on to the next topic: File I/O

25 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”);

26 Java 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.)

27 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 separate

28 Types of InputStreams (1.0) Java’s InputStreams have six general flavors:

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

30 FilterInputStream Class The FilterInputStream offers a ‘grab bag’ of methods.The FilterInputStream offers a ‘grab bag’ of methods. –Sun: this is the base class for “enhancing input stream functionality” –Eckel: “[they] couldn’t 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)

31 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

32 Hierarchy of BufferedReader

33 BufferedReader in Action Reading 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()

34 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”,true)); outFile.println(“this prints to file ”); outFile.close(); } catch (IOException e) { System.out.println(“problem with file”); } } // DoFileStuff

35 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

36 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! That’s the benefit of using the same decorator object namely, 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”)))

37 The File 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

38 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 i=0;i<=listing.length;i++) System.out.println(listing[i]); } //try catch(Exception bummer) { bummer.printStackTrace(); } } //main } //class

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

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

41 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

42 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

43 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, don’t modify your.java files!

44 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

45 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

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

47 Networking 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.

48 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) Application Transport Network Link User Process Protocol stack in kernel

49 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.)

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

51 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

52 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 */;}

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

54 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

55 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

56 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(); }

57 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


Download ppt "CS 1312 Introduction to Object Oriented Programming Lecture 10 Java’s String class Java File I/O."

Similar presentations


Ads by Google