Download 07slide_ObjectFile_io

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript



Learn about computer files
Use the Path class
Learn about
 Streams
 Buffers
 file organization





Use Java’s IO classes to write to and read from a
file
Create and use sequential data files
Learn about random access files
Write records to a random access data file
Read records from a random access data file
Java Programming File I/O
2

We have seen how objects communicate
with each other. Program often need to
communicate with the outside world. The
means of communication are input (such as a
keyboard) and output (such as the computer
screen). Programs can also communicate
through stored data, such as files.
Java Programming File I/O
3

Volatile (Unstable) storage
 Computer memory or random access memory (RAM)
 Temporary
 Nonvolatile storage (having the property of retaining
data when electrical power fails or is turned off.
 Not lost when computer loses power
 Permanent
 Computer file
 Collection of information stored on nonvolatile device
in computer system
Java Programming File I/O
4

Permanent storage devices






Hard disks
Zip disks
USB drives
Reels or cassettes of magnetic tape
Compact discs
Categories of files by the way they store data
 Text files
 Binary files
Java Programming File I/O
5

Data files
 Contain facts and figures

Program files or application files
 Store software instructions



Root directory
Folders or directories
Path
 Complete list of disk drive plus hierarchy of
directories in which file resides
Java Programming File I/O
6

Work with stored files in application
 Determine whether and where file exists
 Open file
 Write information to file
 Read data from file
 Close file
 Delete file
Java Programming File I/O
7
A stream is a communication channel that a
program has with the outside world. It is used to
transfer data items in succession.
An Input/Output (I/O) Stream represents an
input source or an output destination.
A stream can represent many different kinds of
sources and destinations, including disk files,
devices, other programs, and memory arrays.
Java Programming File I/O
8
Reading information into a program
Streams support many different kinds of data, including
simple bytes, primitive data types, localized characters,
and objects.
Some streams simply pass on data; others manipulate
and transform the data in useful ways.
Program uses an input stream to read data from a source, one item at
a time:
Java Programming File I/O
9
A program uses an output stream to write data to a
destination, one item at time:
The data source and data destination pictured above can be
anything that holds, generates, or consumes data. Obviously this
includes disk files, but a source or destination can also another
program, a peripheral device, a network socket, or an array.
Java Programming File I/O
10
Notice that there is a block
of code preceded by the
keyword try and another
block of code preceded by
the keyword finally. This is
to ensure that the code in
the finally block gets
executed, even if the code
within the try block causes
an exception to be thrown.
Java Programming File I/O
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class IOTest {
public static void copyCharacters() throws IOException {
FileReader inputStream = null;
FileWriter outputStream = null;
try {
inputStream = new FileReader("xanadu.txt");
outputStream = new FileWriter("xanadu_output.txt");
int c;
while ((c = inputStream.read()) != -1) {
outputStream.write(c);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}
11
}
Scanner inFile = new Scanner(new File(“in.txt"));
String line;
while (inFile.hasNextLine())
{
line = inFile.nextLine();
// …
}
Java Programming File I/O
12
Copy Characters
example to use lineoriented I/O. To do this,
we have to use two
classes we haven't seen
before, Buffered Reader
and Print Writer.
Java Programming File I/O
import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.IOException;
public static void copyLines() throws IOException {
BufferedReader inputStream = null;
PrintWriter outputStream = null;
try {
inputStream =
new BufferedReader(new FileReader("xanadu.txt"));
outputStream =
new PrintWriter(new FileWriter("characteroutput.txt"));
String l;
while ((l = inputStream.readLine()) != null) {
outputStream.println(l);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}
13
• Use Scanner with File:
Scanner inFile = new Scanner(new File(“in.txt”));
• Similar to Scanner with System.in:
Scanner keyboard = new Scanner(System.in);
• Reading in
Scanner inFile = new Scanner(new File(“in.txt"));
int number;
while (inFile.hasInt())
{
number = inFile.nextInt();
// …
}
Java Programming File I/O
14
// Name, id, balance
Scanner inFile = new Scanner(new File(“in.txt"));
while (inFile.hasNext())
{
name = inFile.next();
id = inFile.nextInt();
balance = inFile.nextFloat();
// … new Account(name, id, balance);
}
-------------------String line;
while (inFile.hasNextLine())
{
line = inFile.nextLine();
Scanner parseLine = new Scanner(line) // Scanner again!
name = parseLine.next();
id = parseLine.nextInt();
balance = parseLine.nextFloat();
// … new Account(name,
id, balance);
Java Programming File I/O
15
The Scanner class is available in Java 5 (JDK 1.5). It
provides methods to convert text into appropriate Java
types (integer, float, etc).
A scanner splits text into a succession of tokens (text
representations of data values) according to specific rules.
For example, in the String object "ab*cd 12.34 253",
"ab*cd" is a String token, "12.34" is a double token and
"253" is an integer token.
Java Programming File I/O
16
By default, a scanner uses
white space to separate tokens.
(White space characters
include blanks, tabs, and line
terminators.
The program that reads the
individual words in xanadu.txt
and prints them out, one per
line.
Java Programming File I/O
import java.io.*;
import java.util.Scanner;
public class ScanXan {
public static void main(String[] args)
throws IOException {
Scanner s = null;
try {
s = new Scanner(new
BufferedReader(new
FileReader("xanadu.txt")));
while (s.hasNext()) {
System.out.println(s.next());
}
} finally {
if (s != null) {
s.close();
}
}
}
17
Java Programming File I/O
18
Java Programming File I/O
19
Java Programming File I/O
20
Java Programming File I/O
21
Java Programming File I/O
22

Retain data for any significant amount of time
 Save on permanent, secondary storage device

Businesses store data in hierarchy





Character
Field
Record
Files
Sequential access file
 Each record stored in order based on value in some
field
Java Programming File I/O
23
Java Programming File I/O
24

Open file
 Create object
 Associate stream of bytes with it

Close file
 Make it no longer available to application
 Should always close every file you open

Stream
 Bytes flowing into program from input device
 Bytes flow out of application to output device
 Most streams flow in only one direction
Java Programming File I/O
25
Java Programming File I/O
26
Java Programming File I/O
27
Java Programming File I/O
28
Java Programming File I/O
29

Sequential access files
 Access records sequentially from beginning to end
 Good for batch processing
▪ Same tasks with many records one after the other
 Inefficient for many applications

Realtime applications
 Require immediate record access while client
waits
Java Programming File I/O
30

Random access files
 Records can be located in any order
 Also called direct access or instant access files

File channel object
 Avenue for reading and writing a file
 You can search for a specific file location and
operations can start at any specified position

ByteBuffer wrap() method
 Encompasses an array of bytes into a
ByteBuffer
Java Programming File I/O
31
Java Programming File I/O
32
Java Programming File I/O
33

Process random access file
 Sequentially
 Randomly
Java Programming File I/O
34

ReadEmployeesSequentially
application
 Reads through 1000-record
RandomEmployees.txt file sequentially in a for
loop (shaded)
 When ID number value is 0
▪ No user-entered record stored at that point
▪ Application does not bother to print it
Java Programming File I/O
35

Display records in order based on key field
 Do not need to create random access file
 Wastes unneeded storage
 Instead sort records

Benefit of using random access file
 Retrieve specific record from file directly
 Without reading through other records
Java Programming File I/O
36
Java Programming File I/O
37

Files
 Objects stored on nonvolatile, permanent storage

File class
 Gather file information

Java views file as a series of bytes
 Views stream as object through which input and
output data flows

DataOutputStream class
 Accomplish formatted output
 Random access files
Java Programming File I/O
38