CS4812 Java - PowerPoint PPT Presentation

1 / 30
About This Presentation
Title:

CS4812 Java

Description:

Java's JDK 1.02 contained particularly weak IO design. Many classes just didn't work. ... Another important object in Java's IO library is the File Class ... – PowerPoint PPT presentation

Number of Views:42
Avg rating:3.0/5.0
Slides: 31
Provided by: davidd1
Category:
Tags: cs4812 | java | javas

less

Transcript and Presenter's Notes

Title: CS4812 Java


1
CS4812 Java
  • Lecture 1
  • File I/O Fun with Streams

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

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

4
Java IO -- Basic Divisions (1.0)
Java I/O is divided up 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
5
Types of InputStreams (1.0)
Javas InputStreams have six general flavors
Watch this class
6
Decorator Classes
  • Java IO uses decorator objects to provide
    layers of functionality to IO classes

Concept A decorator pattern wraps your inner
object, all using the same interface devices.
Pro/Con Flexibility with the cost of
complexity Example notice how may IO classes
feature the readLine() method.
7
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)
8
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
    )
  • bReader new BufferedReader(iStreamReader)
  • // constructor

9
Hierarchy of BufferedReader
10
BufferedReader in Action
  • public String readLine()
  • String strInput ""
  • try strInput bReader.readLine()
  • catch (Exception e)
  • System.err.println (Keyboard error\n\t"
  • e.toString())
  • e.printStackTrace()
  • System.exit(0)
  • return strInput
  • // readLine()

11
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

12
Using File to Obtain A Directory Listing
  • public class Lister
  • public static void main (String arg)
  • try
  • File path new File (.)
  • String listing path.list()
  • for(int ilisting.length i--gt 0)
  • System.out.println(listingi)
  • //try
  • catch(Exception dammit) dammit.printStackTrace()
  • //main
  • //class

13
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().toLowerC
    ase()
  • / 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()

14
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 from on disk or on a
    network.

15
Object Serialization
  • You may have heard about object persistence as
    a new Java buzzword.
  • The Serializable interface provides this
    capabilities 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

16
Object Serialization--More
  • 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 (e.g.,
    the Dots.java class), and save approrpiately

17
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 Dots.java files!

18
Externalization of Objects
  • JDK 1.1 also has the java.io.Externalizable
    class.
  • Externalization is different from serialization.
  • Th 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

19
Externalized Objects--More
  • 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

20
Serialization the transient State
  • There may be 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.

21
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 for purposes of p1.

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

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

24
Ports Sockets What?
  • Generally, computers possess only a single
    physical connection to a network. All
    information arrives and departs through this
    connection. To 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.

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

26
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)
  • catch (MalformedURLException e)
  • System.err.println (This method
    e.toString())
  • URLs can also be created relative to an existing
    URL
  • try
  • URL firstURL new URL(http//www.foo.com/top_le
    vel)
  • URL secondURL
  • new URL (firstURL, lower_level)
  • catch (Exception e)

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

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