Title: COMPE 438 JAVA PROGRAMMING
1COMPE 438JAVA PROGRAMMING
2Object-Oriented Application Frameworks
3Overview
- Application Frameworks
- The Graphical User Interfaces Framework
- The Collections Framework
- The Input/Output Framework
4I/O Overview
- Data is input from and output to programs
- Input From
- Keyboard or a file
- Output to
- Display (screen) or a file
- Text files Vs Binary files
- Text files
- represent printable characters Human readable
- Binary files
- represent other types encoded information, such
as executable files, images or sounds
5I/O Overview
- Advantages of File I/O
- Permanent copy
- The data is lost when a local variable goes out
of scope or when the program terminates - use files for long-term retention of large
amounts of data, even after the programs that
created the data terminated - file processing is one of the most important
capabilities a language must have to support
commercial applications, which typically store
and process massive amounts of persistent data - Output from one program can be input to another
- Input can be automated (rather than entered
manually)
6The Input/Output Framework
- flexible and easily configurable
- support two types of input/output
- Stream I/O (sequential access)
- Stream-based
- Reading or writing sequentially
- may be opened for reading or writing, but not
both - Random Access I/O (random access)
- Reading or writing at any position of a file
- may be opened for both reading and writing
7Streams
- Stream an object that either delivers data to
its destination (screen, file, etc.) or that
takes data from a source (keyboard, file, etc.) - it acts as a buffer between the data source and
destination - Input stream a stream that provides input to a
program - System.in is an input stream
- Output stream a stream that accepts output from
a program - System.out is an output stream
- A stream connects a program to an I/O object
- System.out connects a program to the screen
- System.in connects a program to the keyboard
8Stream I/O
- Java communicates with the outside world using
streams - A stream is a sequence of data
- Java view each file as a sequential streams of
bytes
A program uses an input stream to read data from
a source, one item at a time
A program uses an output stream to write data to
a destination, one item at time
If you want to read and write the same
destination, you use 2 streams
9Binary vs. Text Files
- All data and programs are ultimately just zeros
and ones - each digit can have one of two values, hence
binary - bit is one binary digit
- byte is a group of eight bits
- Text files the bits represent printable
characters - one byte per character for ASCII, the most common
code - for example, Java source files are text files
- Binary files the bits represent other types of
encoded information, such as executable
instructions or numeric data - these files are easily read by the computer but
not humans - they are not "printable" files, "printable" means
"easily readable by humans when printed"
10JavaBinary vs. Text Files
- Text files are more readable by humans
- Binary files are more efficient
- computers read and write binary files more easily
than text - Java binary files are portable
- they can be used by Java on different machines
- Reading and writing binary files is normally done
by a program - text files are used only to communicate with
humans
11JavaBinary vs. Text Files
- Number 127
- Text file
- Three bytes 1, 2, 7
- ASCII (decimal) 49, 50, 55
- ASCII (octal) 61, 62, 67
- ASCII (binary) 00110001, 00110010, 00110111
- Binary file
- One byte (byte) 01111110
- Two bytes (short) 00000000 01111110
- Four bytes (int) 00000000 00000000 00000000
01111110
12Streams
STORE the vaLue 5
101
- byte streams
- Storing data in its binary format
- Binary files
- character streams
- Storing data as a sequence of characters
- Text files
13Byte Streams
public class CopyBytes public static void
main(String args) throws IOException
FileInputStream in null FileOutputStream
out null try in new
FileInputStream(input.txt") out new
FileOutputStream("output.txt") int c
while ((c in.read()) ! -1)
out.write(c) finally if
(in ! null) in.close() if (out !
null) out.close()
14Characters Streams
public class CopyCharacters public static
void main(String args) throws IOException
FileReader in null FileWriter out
null try in new FileReader
(input.txt") out new FileWriter
("characteroutput.txt") int c while ((c
in.read()) ! -1) out.write(c)
finally if (in ! null)
in.close() if (out ! null)
out.close()
15Buffered Streams
- unbuffered I/O
- each read or write request is handled directly by
the underlying OS - less efficient, since each such request often
triggers disk access, network activity, or some
other operation that is relatively expensive
16Buffering
- Not buffered each byte is read/written from/to
disk as soon as possible - little delay for each byte
- A disk operation per byte---higher overhead
- Buffered reading/writing in chunks
- Some delay for some bytes
- Assume 16-byte buffers
- Reading access the first 4 bytes, need to wait
for all 16 bytes are read from disk to memory - Writing save the first 4 bytes, need to wait for
all 16 bytes before writing from memory to disk - A disk operation per a buffer of bytes---lower
overhead
17Buffered Streams
Buffer A small memory location that you use to
hold data temporarily
- buffered I/O
- Buffered input streams read data from a memory
area known as a buffer the native input API is
called only when the buffer is empty. - buffered output streams write data to a buffer,
and the native output API is called only when the
buffer is full.
in new BufferedReader(new FileReader(input.txt"
)) out new BufferedWriter(new
FileWriter(output.txt"))
18Buffered Streams
- four buffered stream classes used to wrap
unbuffered streams - BufferedInputStream and BufferedOutputStream
create buffered byte streams, - BufferedReader and BufferedWriter create buffered
character streams.
19Line-Oriented I/O
- Character I/O usually occurs in bigger units than
single characters - One common unit is the line a string of
characters with a line terminator at the end. - A line terminator can be a carriage-return/line-fe
ed sequence ("\r\n"), a single carriage-return
("\r"), or a single line-feed ("\n") - Supporting all possible line terminators allows
programs to read text files created on any of the
widely used operating systems
20Line-Oriented I/O
public class CopyCharacters public static
void main(String args) throws IOException
FileReader in null FileWriter out
null try in new
BufferedReader(new FileReader(input.txt"))
out new PrintWriter(new
FileWriter("output.txt")) String l
while ((l in.readLine()) ! null)
out.println(l)
finally if (in ! null) in.close()
if (out ! null) out.close()
21Text File Output
- To open a text file for output connect a text
file to a stream for writing - PrintWriter outputStream new PrintWriter(new
FileOutputStream("out.txt")) - Similar to the long way
- FileOutputStream s new FileOutputStream("out.txt
") - PrintWriter outputStream new PrintWriter(s)
- Goal create a PrintWriter object
- which uses FileOutputStream to open a text file
- FileOutputStream connects PrintWriter to a text
file.
22Closing a File
- An output file should be closed when you are done
writing to it (and an input file should be closed
when you are done reading from it). - For example, to close the file opened in the
previous example - outputStream.close()
- If a program ends normally it will close any
files that are open
23Text File Input
- To open a text file for input connect a text
file to a stream for reading - Goal a BufferedReader object,
- which uses FileReader to open a text file
- FileReader connects BufferedReader to the text
file - For example
- BufferedReader smileyInStream
- new BufferedReader(new FileReader(smiley.txt"))
- Similarly, the long way
- FileReader s new FileReader(smiley.txt")
- BufferedReader smileyInStream new
BufferedReader(s)
24Exception Handling with File I/O
- IOException is a predefined class
- File I/O might throw an IOException
- catch the exception in a catch block that at
least prints an error message and ends the
program - FileNotFoundException is derived from IOException
- therefor any catch block that catches
IOExceptions also catches FileNotFoundExceptions - put the more specific one first (the derived one)
so it catches specifically file-not-found
exceptions - then you will know that an I/O error is something
other than file-not-found
25Writing Formatted File Data
- Use the DataInputStream and DataOutputStream
classes to accomplish formatted input and output - DataOutputStream objects enable you to write
binary data to an OutputStream - When you use a DataOutputStream connected to
FileOutput Stream, this is known as chaining the
stream objects
26Data Streams
- Data streams support binary I/O of primitive data
type values (boolean, char, byte, short, int,
long, float, and double) as well as String values - All data streams implement either the DataInput
interface or the DataOutput interface - the most widely-used implementations of these
interfaces, DataInputStream and DataOutputStream
27Writing Formatted File Data
- The DataOutput interface includes methods such
as - writeBoolean()
- writeChar()
- writeDouble()
- writeFloat()
- writeInt()
28Reading Formatted File Data
- DataInputStream objects enable you to read binary
data from an InputStream - DataInput interface is implemented by
DataInputStream
29Reading Formatted File Data
- The DataInput interface includes methods such as
- readByte()
- readChar()
- readDouble()
- readFloat()
- readInt()
- readUTF()
30Using the File Class
- File class does not provide any opening,
processing, or closing capabilities for files - use the File class to obtain information about a
file, such as whether it exists or is open, its
size, and its last modification date - must include the statement
- import java.io.
- create a File object using a constructor that
includes a filename - File someData new File(data.txt)
31Using the File Class
32Random Access Files
- Streams provide a simple model for reading and
writing data. Streams work with a large variety
of data sources and destinations, including disk
files. - However, streams don't support all the operations
that are common with disk files - non-stream file I/O
- File, examines and manipulates files and
directories. - Random access files , support nonsequential
(random) access to disk file data.
33Random Access Files
- Sequential access files access records in
sequential order from beginning to end - Random access files are files in which records
can be accessed in any order - Also called direct access files
- More efficient than sequential access files
- examples of a good use of random access files
- zip files
- real-time applications
34Random Access Files
- An efficient way to extract a particular file
from within a zip file is with a random access
file - open the file
- find and read the directory locating the entry
for the desired file - seek to the position of the desired file
- read it
- With a sequential access file, on average you'd
have to read half the zip file before finding the
file that you wanted. With a random access file,
you only read the directory and the file that you
need.
35Create Random Access Files
- The RandomAccessFile class contains the same
read(), write() and close() methods as
InputStream and OutputStream - Also contains seek() that lets you select a
beginning position within the file before reading
or writing data - Use Java's RandomAccessFile class to create your
own random access files
36Create Random Access Files (Examples)
- The following code creates a RandomAccessFile to
read the file named input.txt - new RandomAccessFile(input.txt", "r")
- The following one opens the same file for both
reading and writing - new RandomAccessFile(output.txt", "rw")
- After the file has been opened, you can use the
common read or write methods defined in the
DataInput and DataOutput interfaces to perform
I/O on the file. -
37Random Access Files File Pointer
- RandomAccessFile supports the notion of a file
pointer. - The file pointer indicates the current location
in the file. - RandomAccessFile contains three methods for
explicitly manipulating the file pointer. - 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 -
38EXAMPLES(Reading Text from Standard Input)
try BufferedReader in new
BufferedReader(new InputStreamReader(System.i
n)) String str while ((str ! null)
str in.readLine()
System.out.println(str) catch
(IOException e)
39EXAMPLES(Reading Text from File)
try BufferedReader in new
BufferedReader(new
FileReader(content.txt")) String str while
((str in.readLine()) ! null)
System.out.println(str) in.close()
catch (IOException e)
40EXAMPLES(Writing to File)
try BufferedWriter out new
BufferedWriter(new
FileWriter("outfilename"))
out.write("aString") out.close() catch
(IOException e)
If the file does not already exist, it is
automatically created.
41EXAMPLES(Append to a File)
try BufferedWriter out new
BufferedWriter(new
FileWriter(filename, true))
out.write("aString") out.close() catch
(IOException e)
42EXAMPLES(Using a Random Access File)
try File f new File("filename")
RandomAccessFile raf new RandomAccessFile(f,
"rw") // Read a character char ch
raf.readChar() // Seek to end of file
raf.seek(f.length()) // Append to the
end raf.writeChars("aString")
raf.close() catch (IOException e)