41
CS203 Programming with Data Structures Input and Output California State University, Los Angeles

CS203 Programming with Data Structures Input and Output California State University, Los Angeles

Embed Size (px)

Citation preview

Page 1: CS203 Programming with Data Structures Input and Output California State University, Los Angeles

CS203 Programming with Data StructuresInput and Output

California State University, Los Angeles

Page 2: CS203 Programming with Data Structures Input and Output California State University, Los Angeles

Overview

Java IDEsPackageInput and outputException handling

Page 3: CS203 Programming with Data Structures Input and Output California State University, Los Angeles

Java IDEs

JBuilder Commercial with a scaled-down free version

(JBuilder Foundation)

Eclipse http://www.eclipse.org High quality and free Many tools and plug-ins have to be installed

separately

Netbeans http://www.netbeans.org All-in-one package Slow on older computers

Page 4: CS203 Programming with Data Structures Input and Output California State University, Los Angeles

IDE Usage Statistics

Survey by BZ Research in December 2005 Eclipse: 65.1% JBuilder: 19.2% Netbeans: 17.9%

Page 5: CS203 Programming with Data Structures Input and Output California State University, Los Angeles

Package

Why do we need it?What does it do?Package and directory

Page 6: CS203 Programming with Data Structures Input and Output California State University, Los Angeles

Input and Output

Console Scanner System.out

GUIFile Reader and Writer InputStream and OutputStream Scanner

Command line parameters

Page 7: CS203 Programming with Data Structures Input and Output California State University, Los Angeles

Understand java.io Package

http://java.sun.com/j2se/1.5.0/docs/api/java/io/package-summary.html

Page 8: CS203 Programming with Data Structures Input and Output California State University, Los Angeles

Stream Types

Character streams Textual information Handled by Reader and Writer classes

Byte streams Binary information Handled by InputStream and

OutputStream classes

Page 9: CS203 Programming with Data Structures Input and Output California State University, Los Angeles

Reader Classes

BufferedReader

ByteArrayReader

InputStreamReader

FilterReader

PipedReader

StringReader

LineNumberReader

FileReader

PushbackReaderReader

Page 10: CS203 Programming with Data Structures Input and Output California State University, Los Angeles

Writer Classes

BufferedWriter

ByteArrayWriter

OutputStreamWriter

FilterWriter

PipedWriter

StringWriter

FileWriterWriter

Page 11: CS203 Programming with Data Structures Input and Output California State University, Los Angeles

InputStream Classes

FileInputStream

PipedInputStream

FilterInputStream

ByteArrayInputStream

SequenceInputStream

StringBufferInputStream

LineNumberInputStream

BufferedInputStream

PushbackInputStreamInputStream

ObjectInputStream

DataInputStream

Page 12: CS203 Programming with Data Structures Input and Output California State University, Los Angeles

OutputStream Classes

FileOutputStream

PipedOutputStream

FilterOutputStream

ByteArrayOutputStream

ObjectOutputStream

BufferedOutputStreamOutputStream

DataOutputStream

PrintStream

Page 13: CS203 Programming with Data Structures Input and Output California State University, Los Angeles

Basic Streams by Source/Destination

Files FileReader/Writer/InputStream/OutputStream

Threads PipedReader/Writer/InputStream/OutputStream

Memory ByteArrayReader/Writer/InputStream/OutputStream StringReader/Writer StringBufferInputStream

General InputStream, InputStreamReader OutputStream, OutputStreamWriter

Page 14: CS203 Programming with Data Structures Input and Output California State University, Los Angeles

Basic Stream Operations

Basic streams only recognize bytes or charactersOperations Read/write a single byte or character Read/write an array of bytes or

characters

Inconvenient

Page 15: CS203 Programming with Data Structures Input and Output California State University, Los Angeles

Wrapper Streams by Function

Data conversion DataInputStream/OutputStream

Printing PrintStream

Buffering BufferedReader/Writer/InputStream/

OutputStream

Object serialization ObjectInputStream/OutputStream

Others

Page 16: CS203 Programming with Data Structures Input and Output California State University, Los Angeles

Important Wrapper Streams and Operations

DataInputStream and DataOutputStream Read and write primitive types readInt(), readDouble(), … writeInt( int i ), writeDoube( double d ), …

BufferedReader readLine()

BufferedWriter write( String s )

Page 17: CS203 Programming with Data Structures Input and Output California State University, Los Angeles

“Wrapping” Examples

// buffered text file read/writeBufferedReader br = new BufferedReader( new FileReader(“file”) );BufferedWriter bw = new BufferedWriter( new FileWriter(“file”) );

// un-buffered binary file read/writeDataInputStream di = new DataInputStream( new FileInputStream(“file”) );DataOutputStream do = new DataOutputStream( new FileOutputStream(“file”) );

// buffered binary file read/writeDataInputStream di2 = new DataInputStream( new BufferedInputStream(

new FileInputStream() ) );DataOutputStream do2 = new DataOutputStream( new BufferedOutputStream(

new FileOutputStream() ) );

Page 18: CS203 Programming with Data Structures Input and Output California State University, Los Angeles

How to Choose from Stream Classes

Step 1: Is the data in binary form or textual form? Binary: Input/OutputStream Textual: Reader/Writer

Step 2: What’s the data source or data destination? Files, threads, memory, general

Step 3: How to process the data? Primitive data types, buffering, …

Page 19: CS203 Programming with Data Structures Input and Output California State University, Los Angeles

File Input Example

Read from a file in the following format, and sum up all numbers

31 20 3022 33 –1 4323 33 44 4579 1-10

Page 20: CS203 Programming with Data Structures Input and Output California State University, Los Angeles

Paths

Windows Absolute path

c:\path\to\file Relative path

path\to\file

Unix Absolute path

/path/to/file Relative path

path/to/file

File separators – “/”, “\\”, File.separator

Page 21: CS203 Programming with Data Structures Input and Output California State University, Los Angeles

Exception Handling

throw and throwstry, catch, and finallyException class getMessage() printStackTrace()

Page 22: CS203 Programming with Data Structures Input and Output California State University, Los Angeles

Scanner Class

A Java 1.5 featureIn java.util package

Scanner s = new Scanner(System.in);String param = s.next();int value = s.nextInt();s.close();

int sum = 0;Scanner s2 = new Scanner( new File(“test”) );while( s2.hasNext() ) sum += s2.nextInt();s2.close()

Page 23: CS203 Programming with Data Structures Input and Output California State University, Los Angeles

File Class

Not directly related to I/OCheck file status Is a file or a directory Exist, readable, writable Name, path, parent Length

Perform common file/directory operations Get parent, list children Delete, rename, mkdir

Page 24: CS203 Programming with Data Structures Input and Output California State University, Los Angeles

Binary File vs. Text File

If we can save data in either binary or text form, which one do we choose? File size Convenience Speed

Either way, always use buffering!

Page 25: CS203 Programming with Data Structures Input and Output California State University, Los Angeles

Exercise

Write a program called Copy that copies a files.Your program should take two arguments from the command line: Source file Destination file E.g. java copy test.txt test2.txt

Page 26: CS203 Programming with Data Structures Input and Output California State University, Los Angeles

DataInputStream/DataOutputStream

DataInputStream reads bytes from the stream and converts them into appropriate primitive type values or strings. DataOutputStream converts primitive type values or strings into bytes and output the bytes to the stream.

Page 27: CS203 Programming with Data Structures Input and Output California State University, Los Angeles

Using DataInputStream/DataOutputStream

Data streams are used as wrappers on existing input and output streams to filter data in the original stream. They are created using the following constructors:

public DataInputStream(InputStream instream)public DataOutputStream(OutputStream outstream)

 The statements given below create data streams. The first statement creates an input stream for file in.dat; the second statement creates an output stream for file out.dat.

DataInputStream infile = new DataInputStream(new FileInputStream("in.dat"));DataOutputStream outfile = new DataOutputStream(new FileOutputStream("out.dat"));

Page 28: CS203 Programming with Data Structures Input and Output California State University, Los Angeles

Order and Format

CAUTION: You have to read the data in the same order and same format in which they are stored. For example, since names are written in UTF-8 using writeUTF, you must read names using readUTF. If you keep reading data at the end of a stream, an EOFException would occur. So how do you check the end of a file? You can use input.available() to check it. input.available() == 0 indicates that it is the end of a file.

Page 29: CS203 Programming with Data Structures Input and Output California State University, Los Angeles

Object I/O

ObjectInputStream/ObjectOutputStream enables you to perform I/O for objects in addition for primitive type values and strings.

Page 30: CS203 Programming with Data Structures Input and Output California State University, Los Angeles

The Serializable Interface

Not all objects can be written to an output stream. Objects that can be written to an object stream is said to be serializable. A serializable object is an instance of the java.io.Serializable interface. So the class of a serializable object must implement Serializable.

The Serializable interface is a marker interface. It has no methods, so you don't need to add additional code in your class that implements Serializable.

Implementing this interface enables the Java serialization mechanism to automate the process of storing the objects and arrays.

Page 31: CS203 Programming with Data Structures Input and Output California State University, Los Angeles

Transient Keyword

If an object is an instance of Serializable, but it contains non-serializable instance data fields, can the object be serialized? The answer is no. To enable the object to be serialized, you can use the transient keyword to mark these data fields to tell the JVM to ignore these fields when writing the object to an object stream.

Page 32: CS203 Programming with Data Structures Input and Output California State University, Los Angeles

Continued…

Consider the following class: public class Foo implements java.io.Serializable { private int v1; private static double v2; private transient A v3 = new A(); }class A { } // A is not serializable When an object of the Foo class is serialized, only variable v1 is serialized. Variable v2 is not serialized because it is a static variable, and variable v3 is not serialized because it is marked transient. If v3 were not marked transient, a java.io.NotSerializableException would occur.

Page 33: CS203 Programming with Data Structures Input and Output California State University, Los Angeles

Serializing Arrays

An array is serializable if all its elements are serializable. So an entire array can be saved using writeObject into a file and later restored using readObject.

Page 34: CS203 Programming with Data Structures Input and Output California State University, Los Angeles

Random Access File

All of the streams you have used so far are known as read-only or write-only streams. The external files of these streams are sequential files that cannot be updated without creating a new file. It is often necessary to modify files or to insert new records into files. Java provides the RandomAccessFile class to allow a file to be read from and write to at random locations.

Page 35: CS203 Programming with Data Structures Input and Output California State University, Los Angeles

Continued…

The problem with the stream modelAdvantages of RandomAccessFile Deal with both binary and text files Provide both read and write methods seek(long pos)

… but we don’t use it often. Why?

Page 36: CS203 Programming with Data Structures Input and Output California State University, Los Angeles

File PointerA random access file consists of a sequence of bytes. There is a special marker called file pointer that is positioned at one of these bytes. A read or write operation takes place at the location of the file pointer. When a file is opened, the file pointer sets at the beginning of the file. When you read or write data to the file, the file pointer moves forward to the next data. For example, if you read an int value using readInt(), the JVM reads four bytes from the file pointer and now the file pointer is four bytes ahead of the previous location.

byte

file

byte

byte

byte

byte

byte

byte

byte

byte

byte

byte

byte

file pointer

byte

file

byte

byte

byte

byte

byte

byte

byte

byte

byte

byte

byte

file pointer

(A) Before readInt()

(B) Before readInt()

Page 37: CS203 Programming with Data Structures Input and Output California State University, Los Angeles

RandomAccessFile MethodsMany methods in RandomAccessFile are the same as those in DataInputStream and DataOutputStream. For example, readInt(), readLong(), writeDouble(), readLine(), writeInt(), and writeLong() can be used in data input stream or data output stream as well as in RandomAccessFile streams.

Page 38: CS203 Programming with Data Structures Input and Output California State University, Los Angeles

RandomAccessFile Methods, cont.

void seek(long pos) throws IOException;

Sets the offset from the beginning of the RandomAccessFile stream to where the next reador write occurs.

long getFilePointer() IOException;

Returns the current offset, in bytes, from thebeginning of the file to where the next reador write occurs.

Page 39: CS203 Programming with Data Structures Input and Output California State University, Los Angeles

RandomAccessFile Methods, cont.

long length()IOException

Returns the length of the file.

final void writeChar(int v) throws IOException

Writes a character to the file as a two-byte Unicode, with the high byte written first.

final void writeChars(String s)throws IOException

Writes a string to the file as a sequence ofcharacters.

Page 40: CS203 Programming with Data Structures Input and Output California State University, Los Angeles

RandomAccessFile ConstructorRandomAccessFile raf =new RandomAccessFile("test.dat", "rw"); //allows read and write

RandomAccessFile raf =new RandomAccessFile("test.dat", "r"); //read only

Page 41: CS203 Programming with Data Structures Input and Output California State University, Los Angeles

Fixed Length String I/O

Random access files are often used to process files of records. For convenience, fixed-length records are used in random access files so that a record can be located easily. A record consists of a fixed number of fields. A field can be a string or a primitive data type. A string in a fixed-length record has a maximum size. If a string is smaller than the maximum size, the rest of the string is padded with blanks.

Record 1

Record 2

Record n

Field1 Field 2 … Field k

file e.g.,

Student 1

Student 2

Student n

name street city state zip