CS 424524: Introduction to Java Programming - PowerPoint PPT Presentation

1 / 26
About This Presentation
Title:

CS 424524: Introduction to Java Programming

Description:

IO classes have tools to supports these algorithms. Two types of ... { File inputFile = new File('farrago.txt'); File outputFile = new File('outagain.txt' ... – PowerPoint PPT presentation

Number of Views:20
Avg rating:3.0/5.0
Slides: 27
Provided by: dyes
Category:

less

Transcript and Presenter's Notes

Title: CS 424524: Introduction to Java Programming


1
CS 424/524 Introduction to Java Programming
  • Lecture 13
  • Spring 2002
  • Department of Computer Science
  • University of Alabama
  • Don Yessick

2
Overview
  • I/O Reading and Writing
  • Using the Streams (EOF examples)
  • Object Serialization
  • Random Access Files
  • Zip Files
  • Java.Text (formatting numbers)
  • Parsing Numbers from Strings

3
Streams
  • Sequential Input and Output
  • Pattern for stream processing
  • open stream
  • while more data
  • read/write stream
  • close stream
  • IO classes have tools to supports these
    algorithms

4
Two types of streams
  • Character streams
  • Reader Writer model
  • read() readln()
  • print() println()
  • (ascii / 16-bit (unicode) characters)
  • Byte streams
  • IOstream model
  • readDouble() etc
  • write() etc
  • (binary 8 bit bytes only)

5
Reader vs InputStream
  • Reader (unicode)
  • int read()
  • int read(char cbuf)
  • int read(char cbuf, int offset, int length)
  • InputStream (bytes)
  • int read()
  • int read(byte cbuf)
  • int read(byte cbuf, int offset, int length)
  • both provide methods for marking a location in
    the stream, skipping input, and resetting the
    current position.

6
Writer vs OutputStream
  • Writer (unicode)
  • int write(int c)
  • int write(char cbuf)
  • int write(char cbuf, int offset, int length)
  • OutputStream (bytes)
  • int write(int c)
  • int write(byte cbuf)
  • int write(byte cbuf, int offset, int length)

7
A Reader/Writer Example (EOF)
  • import java.io.
  • public class Copy
  • public static void main(String args) throws
    IOException
  • File inputFile new File(original.txt")
  • File outputFile new File(copy.txt")
  • FileReader in new FileReader(inputFile)
  • FileWriter out new FileWriter(outputFile)
  • int c
  • while ((c in.read()) ! -1) //EOF
    condition test
  • out.write(c)
  • in.close()
  • out.close() //best to close (flushes any
    buffers)

8
Byte Example (EOF)
  • import java.io.
  • public class CopyBytes
  • public static void main(String args) throws
    IOException
  • File inputFile new File("farrago.txt")
  • File outputFile new File("outagain.txt")
  • FileInputStream in new
    FileInputStream(inputFile)
  • FileOutputStream out new
    FileOutputStream(outputFile)
  • int c
  • while ((c in.read()) ! -1) //EOF
    condition test
  • out.write(c)
  • in.close()
  • out.close()

9
Encoding/Internationalization
  • FileReader and FileWriter read and write 16-bit
    characters.
  • These streams encode characters according to the
    default character-encoding scheme. (Most native
    file systems are based on 8-bit bytes.)
  • System.getProperty("file.encoding").
  • To specify an encoding, construct an
    OutputStreamWriter on a FileOutputStream and
    specify the encoding.

10
Working with Filter Streams
  • Filters data being read from or written to a
    stream
  • Some streams buffer data, some count data, others
    convert data to another form.
  • DataInputStream DataOutputStream
  • BufferedInputStream BufferedOutputStream
  • LineNumberInputStream
  • PushbackInputStream (Character based)
  • PrintStream (This is an output stream.)

11
DataInputStream DataOutputStream
  • Conceptually, data looks like this, although in
    binary form (non-ASCII)
  • 19.99 12 Java T-shirt
  • 9.99 8 Java Mug
  • The data might have been created with the
    following
  • DataOutputStream out
  • new DataOutputStream( new FileOutputStream("invoi
    ce1.txt"))
  • for (int i 0 i lt prices.length i )
  • out.writeDouble(pricesi)
    out.writeChar('\t')
  • out.writeInt(unitsi) out.writeChar('\t')
  • out.writeChars(descsi) out.writeChar('\n')
  • out.close()

12
  • DataInputStream in
  • new DataInputStream( new FileInputStream("invoice
    1.txt"))
  • try //exception raised at EOF
  • while (true) char chr
  • price in.readDouble() in.readChar()
    //throws out the tab
  • unit in.readInt() in.readChar() //throws
    out the tab
  • desc new StringBuffer(20)
  • char lineSep System.getProperty("line.separ
    ator").charAt(0)
  • while ((chr in.readChar() ! lineSep) //end
    of line (carriage return linefeed)
  • desc.append(chr)
  • System.out.println("You've ordered " unit "
    units of " desc
  • " at " price)
  • total total unit price
  • catch (EOFException e)
  • System.out.println("For a TOTAL of " total)
  • in.close()

13
ObjectOutputStream (Serialization)
  • FileOutputStream out
  • new FileOutputStream("theTime")
  • ObjectOutputStream s
  • new ObjectOutputStream(out)
  • s.writeObject("Today")
  • s.writeObject(new Date())
  • s.flush()
  • The writeObject method throws a
    NotSerializableException if it's given an object
    that is not serializable. An object is
    serializable only if its class implements the
    Serializable interface.

14
ObjectInputStream (Deserialization)
  • FileInputStream in
  • new FileInputStream("theTime")
  • ObjectInputStream s
  • new ObjectInputStream(in)
  • String today (String)s.readObject()
  • Date date (Date)s.readObject()
  • ObjectInputStream stream implements the DataInput
    interface that defines methods for reading
    primitive data types

15
The Serializable Interface (majik)
  • public class MySerializableClass implements
    Serializable ...
  • Optional
  • private void writeObject(ObjectOutputStream s)
    throws IOException
  • s.defaultWriteObject()
  • // customized serialization code
  • private void readObject(ObjectInputStream s)
    throws IOException
  • s.defaultReadObject()
  • // customized deserialization code ...
  • // followed by code to update the object, if
    necessary
  • See also Externalizable Interface (for total
    control)

16
Random Access Files
  • new RandomAccessFile(data.txt", "rw")
  • int skipBytes(int) --Moves the file pointer
    forward the specified number of bytes
  • void seek(long) --Positions the file pointer just
    before the specified byte
  • long getFilePointer() --Returns the current byte
    location of the file pointer
  • The RandomAccessFile class implements both the
    DataInput and DataOutput interfaces
  • Does not extend stream class
  • No support for Serialized Objects

17
java.util.zip package
  • CheckedInputStream CheckedOutputStream
  • An input and output stream pair that maintains a
    checksum as the data is being read or written.
  • DeflaterOutputStream InflaterInputStream
  • Compresses or uncompresses the data as it is
    being read or written.
  • GZIPInputStream GZIPOutputStream
  • Reads and writes compressed data in the GZIP
    format.
  • ZipInputStream ZipOutputStream
  • Reads and writes compressed data in the ZIP
    format

18
Summary of IO
  • The java.io package contains classes to read and
    write data. Most implement sequential access
    streams. Some read and write bytes and some read
    and write Unicode characters. Each has a
    speciality, such as reading from or writing to a
    file, filtering data, or serializing objects.
  • RandomAccessFile, implements random input/output
    access to a file. An object of this type
    maintains a file pointer indicating the current
    location from which data will be read or written.
  • java.util.zip package contains other useful I/O
    classes.

19
Package java.text
  • Classes and interfaces for handling text, dates,
    numbers, and messages independently of natural
    languages.
  • Applications and applets can be
    language-independent, relying upon separate,
    dynamically-linked localized resources and
    allowing for new localizations at any time.
  • Capable of formatting dates, numbers, and
    messages, parsing searching and sorting strings
    and iterating over characters, words, sentences,
    and line breaks.
  • Three main groups of classes and interfaces
  • Classes for iteration over text
  • Classes for formatting and parsing
  • Classes for string collation

20
DateFormat
  • DateFormat df DateFormat.getDateInstance()
  • for (int i 0 i lt a.length i)
  • output.println(df.format(myDatei) " ")
  • To format a number for a different Locale,
    specify it in the call to getDateInstance().
  • DateFormat df DateFormat.getDateInstance(Locale.
    FRANCE)
  • You can use a DateFormat to parse also.
  • myDate df.parse(myString)

21
NumberFormat
  • myString NumberFormat.getInstance().format(myNum
    ber)
  • Or
  • NumberFormat nf NumberFormat.getInstance()
  • for (int i 0 i lt a.length i)
  • output.println(nf.format(myNumberi) " ")
  • Or
  • NumberFormat nf NumberFormat.getInstance(Locale.
    FRENCH)
  • Parsing
  • myNumber nf.parse(myString)

22
More Number Formats
  • getCurrencyInstance
  • getPercentInstance
  • DecimalNumberFormat
  • Also useful
  • setMinimumFractionDigits

23
Alignment
  • No simple method.
  • Monospaced font
  • examine string length and pad with spaces
  • Proportional font
  • start counting pixels.
  • If Decimal numbers.

24
Parsing Strings to Numbers
  • From class Integer
  • static int parseInt(String s)
  • Parses the string argument as a signed decimal
    integer.
  • static int parseInt(String s, int radix)
  • Parses the string argument as a signed integer in
    the radix specified by the second argument.
  • From class Float
  • static float parseFloat(String s)
  • Returns a new float initialized to the value
    represented by the specified String, as performed
    by the valueOf method of class Double.

25
Parsing Differences
  • Formatted Strings
  • use appropriate Format methods
  • 1,024,512.64
  • 2,345
  • vs Unformatted Strings
  • use static methods of appropriate class
  • 1024512.64
  • 2345

26
Reading Assignment
  • Next Topic Threads
  • Chapter 15
  • Chapter 6.1
Write a Comment
User Comments (0)
About PowerShow.com