Title: The java.io Package
1The java.io Package
- Text files
- Reader and Writer classes
- Byte stream files
- InputStream, FileInputStream, OutputStream,
FileOutputStream - Primitive-data stream files
- DataInputStream, DataOutputStream
- Object stream files
- ObjectInputStream ObjectOutputStream
2The File Class
- A File object represents an abstract pathname.
- Represents both files and directories (folders).
- Name, parent directory, size, permissions.
- Constructor takes the files name
- File info new File("Letter.txt")
- No exception thrown if the file does not exist.
3Methods of the File Class
File info new File("Letter.txt") if(info.exists
()) System.out.println("Size of
"info.getName() " is
"info.length()) if(info.isDirectory())
System.out.println("The file is a
directory.") if(info.canRead())
System.out.println("The file is readable.")
if(info.canWrite())
System.out.println("The file is writeable.")
4FileReader and FileWriter
- The two main classes for reading and writing text
files. - A file is opened when its name is passed to their
constructors. - Files should be closed (via close) when finished
with. - Their read and write methods deal with char and
char.
5Opening and Closing a File
try // Try to open the file. FileReader
inputFile new FileReader(filename) //
Process the file's contents. ... // Close
the file now that it is finished with.
inputFile.close() catch(FileNotFoundException
e) System.out.println("Unable to open
"filename) catch(IOException e) // The
file could not be read or closed.
System.out.println("Unable to process
"filename)
6Copying a Text File
static void copyFile(FileReader inputFile,
FileWriter outputFile)
throws IOException final int
bufferSize 1024 char buffer new
charbufferSize // Read the first chunk of
characters. int numberRead
inputFile.read(buffer) while(numberRead gt
0) // Write out what was read.
outputFile.write(buffer,0,numberRead)
numberRead inputFile.read(buffer)
outputFile.flush()
7Reading Single Characters
static void copyFile(FileReader inputFile,
FileWriter outputFile) try
// Read the first character. int nextChar
inputFile.read() // Have we reached
the end of file? while(nextChar ! -1)
outputFile.write(nextChar)
// Read the next character. nextChar
inputFile.read()
outputFile.flush() catch(IOException
e) System.out.println("Unable to copy a
file.")
8Buffered Reader and Writers
try FileReader in new FileReader(infile)
BufferedReader reader new BufferedReader(in)
FileWriter out new FileWriter(outfile)
BufferedWriter writer new BufferedWriter(out)
... reader.close()
writer.close() catch(FileNotFoundException
e) System.out.println(e.getMessage()) catc
h(IOException e) System.out.println(e.getMess
age())
9Line-by-Line Copying
BufferedReader reader new BufferedReader(...) /
/ Read the first line. String line
reader.readLine() // null returned on
EOF. while(line ! null) // Write the whole
line. writer.write(line) // Add the
newline character. writer.newLine() //
Read the next line. line reader.readLine()
10PrintWriter
try FileWriter out new FileWriter(outfile)
PrintWriter writer new PrintWriter(out)
writer.println() writer.format(d,)
writer.close() catch(IOException e)
System.out.println(e.getMessage())
11System.in
BufferedReader reader new BufferedReader( n
ew InputStreamReader(System.in))
12The StringTokenizer Class
- Defined in the java.util package.
- Splits strings into separate String tokens.
- Delimiter characters are user settable
(whitespace by default). - Will also return delimiters if required.
- Simple interface
- public boolean hasMoreTokens()
- public String nextToken()
13Finding Words
String line in.readLine() while(line !
null) StringTokenizer tokenizer
new StringTokenizer(line,",.\"' \t")
while(tokenizer.hasMoreTokens()) String
word tokenizer.nextToken() // Print
the next word. System.out.println(word)
line in.readLine()
14The Scanner Class
- Defined in the java.util package.
- A scanner can be created from File, InputStream,
or String. - Use useDelimiter to set the delimiting pattern.
- Use next to retrieve the next token and use
nextInt, etc. to retrieve a token of a certain
type.
15Finding Words
String line in.readLine() while(line !
null) Scanner sc new Scanner(line)
sc.useDelimiter(",\\.\"' \t")
while(sc.hasNext()) String word
sc.next() // Print the next word.
System.out.println(word) line
in.readLine()
16The Stream Classes
- Several classes that deliver input as a stream of
raw bytes, or write raw bytes. - BufferedInputStream, FileInputStream.
- BufferedOutputStream,FileOutputStream.
- Their read and write methods take byte rather
than char arguments.
17Manipulating Primitive Data Files
- DataInputStream
- readBoolean(),readChar(),readInt()...
- DataOutputStream
- writeBoolean(),writeChar(),writeInt(),....
18Reading from URLs
import java.net. import java.io. public class
URLReader public static void main(String
args) throws Exception URL yahoo new
URL("http//www.yahoo.com/") BufferedReader in
new BufferedReader( new InputStreamReader(
yahoo.openStream())) String
inputLine while ((inputLine in.readLine())
! null) System.out.println(inputLine) in
.close()
19Review
- Input-Output is usually difficult to perform in a
platform-independent way. - The java.io package provides the required
independence. - The File class supplies details of external
files. - Use Reader and Writer classes for text files.
20Review (cont.)
- Use Buffered classes for input-output efficiency.
- Use Stream classes when access to binary data is
required. - Use DataInputStream and DataOutputStream when
access to primitive data is required - StringTokenizer is useful for breaking up textual
input.