File I/O - PowerPoint PPT Presentation

1 / 14
About This Presentation
Title:

File I/O

Description:

buffer. PrintWriter pw = new PrintWriter(bw); PrintWriter(bw) ... flush output buffer and break connection. Create a PrintWriter to write to an output file ... – PowerPoint PPT presentation

Number of Views:23
Avg rating:3.0/5.0
Slides: 15
Provided by: jamest92
Category:
Tags: file

less

Transcript and Presenter's Notes

Title: File I/O


1
File I/O
Contents
  1. Opening an input file
  2. Writing to an output file
  3. Examining the details of file I/O
  4. Using the String array parameters in function
    main( )
  5. Review of input/output choices

2
File I/O
For many applications the input data will be
stored in a file located on a disk, and the
output will also be directed to a file.
Must already exist when program runs
Dynamically created if it doesnt already exist
3
File I/O
Opening an Input File
FileReader fr new FileReader(a\\input.txt)
BufferedReader br new BufferedReader(fr)
String str br.readLine( )
br.close( )
String stored here
Create a FileReader with the file name and path
supplied as a parameter
4
File I/O
Writing to an Output file
FileWriter fw new FileWriter(a\\output.txt)
BufferedWriter bw new BufferedWriter(fw)
PrintWriter pw new PrintWriter(bw)
pw.println(text text text)
pw.close( )
text text text
text
text text
Create a FileWriter to establish a connection to
an output file. If the file passed as a
parameter does not exist in the specified path,
it is created.
5
File I/O
Examine the details of file I/O
When opening a file you must supply the full path
and file name. If the file input.txt is located
in a directory datafiles on a floppy disk, then
the parameter passed to a file reader would be
FileReader fr new FileReader(a\\datafiles\\inp
ut.txt)
The first backslash character is an escape
character. The second backslash indicates that a
backslash character is actually part of the
string.
a\\datafiles\\input.txt
For example \t tab \n newline \\ \
6
File I/O
Examining the details of file I/O
The statement sequence
FileReader fr new FileReader(a\\datafiles\\inp
ut.txt) BufferedReader br new
BufferedReader(fr)
Can be written as one statement
BufferedReader br new BufferedReader(new
FileReader(a\\datafiles\\input.txt))
The FileReader object, fr, is wrapped inside a
BufferedReader in the first sequence of
statements, and is never directly used no
messages from the code written by the programmer
are directed to it. In the combined statement,
the FileReader object is not given its own
identifier and cannot have programmer generated
messages directed to it.
7
File I/O
Examining the details of file I/O
Similarly the three statements for directing
output to an output file can be combined into a
single statement.
FileWriter fw new FileWriter(a\\output.txt)
BufferedWriter bw new BufferedWriter(fw) PrintW
riter pw new PrintWriter(bw)
Are written as a single statement
PrintWriter pw new PrintWriter(new
BufferedWriter( new FileWriter(a\\output.txt)
))
8
File I/O
Examining the details of file I/O
There are a number of exceptions that may occur
when working with files. The input file may not
exist, the output file may be unavailable,
reading from or writing to a file may cause an
exception. File I/O should (must) be done inside
of a try block.
try BufferedReader br new
BufferedReader(new FileReader(input.txt))
//do this repeatedly String str
br.readLine( ) //process the string str
PrintWriter pw new PrintWriter(new
BufferedWriter( new FileWriter(output.txt)))
pw.println(output text string) //this
may be done repeatedly in a loop
9
File I/O
Explaining the details of file I/O
The catch block (or blocks) must directly follow
a try block. One may catch a sequence of
individual IOExceptions (FileNotFound, EOF,
Interrupted, etc.), or one may have a single
catch-all catch block. Unless one intends to
handle each kind of exception differently, the
single catch block makes the most sense.
catch (Exception e) System.out.println(e.
toString( )) finally try
br.close( ) pw.close( ) catch
(Exception e) //do nothing
An optional finally block can be used to execute
code whether the try block terminates with or
without exception.
In this example closing files is done in the
finally block
10
File I/O
An example
import java.io. //for File I/O import
java.util. //for StringTokenizer class
FileIOExample public static void
main(String args) try
BufferedReader in new BufferedReader(new
FileReader(input.txt)) String
inStr in.readLine( ) //assume all input data
on a single line in.close( )
double sum 0.0, term
PrintWriter out new PrintWriter(new
BufferedWriter(new FileWriter(output.txt)))
StringTokenizer st new
StringTokenizer(inStr) while
(st.hasMoreTokens( )) term
Double.parseDouble(st.nextToken( ))
out.println(term) //echo each number back to
the ouput file sum term
out.println(The sum is
sum) out.close( ) //end
of try block
//finish reading data close the input file
//flush output buffer and break connection
11
File I/O
Explaining the details of file I/O
A FileReader is used to construct a pipe from a
file to a program. However, it can only be used
to read a single character at a time.
d
a
t
a
FileReader fr new FileReader(input.dat)
String str
char ch (char) fr.read( ) //called 4 times
str br.readLine( )
12
File I/O
Explaining the details of file I/O
An output file behaves similarly. By wrapping a
PrintWriter around a BufferedWriter each print( )
and println( ) message causes text to be written
to a buffer in main memory.
When the close( ) message is sent to the
PrintWriter object, the message is relayed
(transparently) to the BufferedWriter. The
BufferedWriter writes the contents of the buffer
to the disk before the connection to the output
file is broken. The programmer can direct disk
writes to occur at certain points in the
execution of the program by sending the flush( )
message to the PrintWriter object.
13
File I/O
Why the parameters String args in the header
for function main?
Instead of hardwiring in the identities of the
input and output files like we have done in the
previous examples writing the names of the
files directly into the code we can supply a
file name and path when we run the program by
using these parameters.
class FileIOExample2 public static void main
(String args) try
BufferedReader br new BufferedReader(new
FileReader(args0)) PrintWriter pw
new PrintWriter(new BufferedWriter(
new FileWriter(args1))) //rest of
function //end of try block catch
(IOException e) System.out.println(e) exit(1)
When running this program from the command line
you will type
cgtjava FileIOExample2 input.txt output.txt
14
File I/O
We now have three ways of performing I/O
From keyboard to screen
Using Dialog Boxes
Using File I/O
import java.io.
import javax.swing.
import java.io.
input
input
input
BufferedReader wraps InputStreamReader wraps
System.in
JOptionPane. showInputDialog(mssg) Returns a
String
BufferedReader wraps a FileReader(fname)
output
output
output
System.out.println( )
JOptionPane. showMessageDialog()
PrintWriter wraps BufferedWriter
wraps FileWriter(filename)
Write a Comment
User Comments (0)
About PowerShow.com