Download Programming in Java

Document related concepts
no text concepts found
Transcript
Lecture12
12-1
Input & Output
in Java
Application
Program
JOHN DOE'S
DISK
MYFILE.DAT
Programming in Java
Objectives
Perform stream input/output with the core classes in the
package java.io
•
•
Use the standard streams System.in, System.out System.err
 Distinguish between byte-oriented and character-oriented streams

Write code that uses objects of the file class to navigate a file system

Select valid constructor for FilterInputStream and
FilterOutputStream subclasses from a list of classes in the java.io
package

Write appropriate code to read,write,and update files using
FileInputStream,FileOutputStream,and RandomAccessFile objects
Programming in Java
12-2
java.io
• Standard Java package
Define classes for Input/Output
Very general
-Support console,files,netwoek connections,…
-Support raw IO, formatted IO,…
The package does not provide facilities for drawing
or displaying graphical components on the screen
Also it does not support the mouse
• Based on Stream input and output
i.e., raw input/output consists of a stream of bytes
We just treat each byte as a binary value
Programming in Java
12-3
Streams
12-4
• A stream is an abstraction of the continuous one-way flow of
data.
– no inherent records or lines; no direct access to any locations
Input Stream
Program
File
Output Stream
Programming in Java
Input Streams vs.Output Stream
• Java uses streams to facilitate input and output
operations
• Input streams are used to “read” data
• Output streams are used to “write” data
Programming in Java
12-5
Java I/O
Programming in Java
12-6
Java I/O Streams(1)
12-7
• Streams can also be viewed as the endpoints of a
one-way communications channel, which connects
an output stream to a corresponding input stream
write
Output Stream
Communications Channel
Input Stream
read
• Everything that is written to the output stream
can be read from the input stream
Programming in Java
Java I/O Streams(2)
• The communications channel can be a network
link, a memory buffer, a file, or a terminal to the
user
• No matter where the information is coming from
or going to and no matter what type of data is
being read or written, the algorithms for reading
and writing data are pretty much the same
• Streams can, therefore, provide a uniform
interface
Programming in Java
12-8
Java I/O Streams(3)
• Streams are FIFO (first-in first-out)
– e.g., if a sequence of numbers is written to an output
stream, they will be written to their destination in the
same order and read from a corresponding input stream
in the same order
– exception: RandomAccessFile
• Blocking I/O
– reads and writes must wait for the I/O operation to
complete before returning
Programming in Java
12-9
Characters Streams vs. Bytes Streams
• The java.io package contains a collection
of stream classes
– These classes are divided into two class
hierarchies based on the data type (either
characters or bytes) on which they operate
Programming in Java
12-10
Bytes Stream
• InputStream and OutputStream are the
abstract superclasses for byte streams in Java
InputStream provides the API and partial
implementation for input streams
--streams that read 8-bit bytes
OutputStream provides the API and partial
implementation for output streams
--streams that write 8-bit bytes
• These streams are typically used to read
and write binary data such as images and
sounds
Programming in Java
12-11
Byte-Oreiented Stream Classes
12-12
ByteArrayInputStream
DataInputStream
InputData
FileInputStream
BufferedInputStream
FilterInputStream
LineNumberInputStream
InputStream
SequenceInputStream
PushBackInputStream
PipedInputStream
ObjectInputStream
Object
ObjectInput
StringBufferInputStream
ByteArrayOutputStream
FileOutputStream
OutputStream
FilterOutputStream
PipeOutputStream
ObjectOutputStream
BufferedOutputStream
DataOutputStream
PrintStream
ObjectOutput
RandomAccessFile
Programming in Java
OutputData
Subclasses of InputStream and OutputStream
FileDescriptor
Object
File
StreamTokenizer
OutputStream
InputStram
DataOutput
RandomAcessFile
DataInput
SequenceInputStream
StringBufferInputStream
ByteArrayOutputStream
PipedOutputStream
PipedInputStream
FileInputStream
FileOutputStream
FilterInputStream
FilterOutputStream
PrintStream
BufferedOutputStream
DataOutputStream
ByteArrayInputStream
LineNumberInputStream
BufferedInputStream
DataInputStream
PushbackInputStream
Programming in Java
12-13
Predefined Stream Objects
12-14
• All java programs can use three stream objects that
are defined in the System class
– System.in
• is a java.io.BufferedInputStream object
• this object encapsulates keyboard input
– System.out
• is a java.io.PrintStream object
• this object encapsulates output to a command-line
window and is used for most command-line mode
output
• can redirect the output to a file
– System.err
• is a java.io.PrintStream object
• Output sent to System.err goes to a command line and
can be mixed with output to System.out
Programming in Java
Input and Output Methods
InputStream:
• abstract int read() throws IOException
• int read(byte b[]) throws IOException
• void close() throws IOException
• void available() throws IOException
• long skip(long n) throws IOException
OutputStream:
• abstract void write(int b) throws IOException
• void write(byte[] b) throws IOException
• void close() throws IOException
• void flush() throws IOException
Programming in Java
12-15
InputStream Example
import java.io.*; //计算文件中的字符数和空白字符数
class CountSpace{
public static void main(String[] args) throws IOException
{ InputStream in;
if (args.length==0) in=system.in;
else in=new FileInputStream(args[0]);
int ch; int total; int spaces=0;
for(total=0;(ch=in.read())!=-1;total++){
if (Charater.isSpace((char)ch) spaces++;
}
System.out.println(total+”chars,”+spaces+”spaces”);
}
}
Programming in Java
12-16
OutputStream Example(1)
import java.io.*;//将输入的数据拷贝输出,并转化特定字符
class Translate{
public static void main(String[] args){
InputStream in=System.in;
OutputStream out=System.out;
if (args.length!=2)
error(“from/to needed”);
String from=args[0], to=args[1];
int ch,i;
if (from.length()!=to.length())
error(“same length needed”);
Programming in Java
12-17
OutputStream Example(2)
try{ while((ch=in.read())!=-1){
if ((i=from.indexOf(ch))!=-1)
out.write(to.charAt(i));
else out.write(ch);
}
}catch(IOException e) { error(“I/O Exception:”+e); }
}
public static void error(String err){
System.err.print(“Translate:”+err);
System.exit(1); //非零值意指“不好”
}
}
Programming in Java
12-18
Filtered Streams
• when you want to do more than read and write
bytes and chars ...
– Stream filters provide enhanced functionality on top of
other existing streams
– The basic approach is to layer stream filters on top of
more primitive streams
– Filter streams add new constructors to the basic ones in
the InputStream and OutputStream classes, and enable
you to chain streams to produce composite streams of
greater power
Programming in Java
12-19
Byte-oriented Filter Streams
12-20
FilterInputStream, FilterOutputStream:
• DataInputStream, DataOutputStream
– These classes transmit data of specific types across a stream instead
of treating a stream as a sequence of independent bytes.You can
also call methods of these classes to read and write the binary
representations of the primitives types
• BufferedInputStream, BufferedOutputStream
– These classes provide buffering for input and output operations
• PrintStream
– This class implements methods for displaying data types
textually(print,println)
• PushbackInputStream
– This class maintains a one-byte push-back buffer
• LineNumberInputStream
– provides an object to keep track of line numbers while reading
input
Programming in Java
Data Streams and Interfaces
•
While reading and writing bytes is useful, there is also
a frequent need to transmit data of specific types across
a stream
•
The DataInput and DataOutput interfaces defines
methods to transmit Java primitive types across a
stream
•
A default implementation of each interface is provided
by the classes DataInputStream and DataOutputStream
Programming in Java
12-21
Basic input/output method
Read
Write
Type
readBoolean
writeBoolean
boolean
readChar
writeChar
char
readByte
writeByte
byte
readShort
writeShort
short
readInt
writeInt
int
readLong
writeLong
long
readFloat
writeFloat
float
readDouble
writeDouble
double
readUFT
writeUFT
String(UTF format)
Programming in Java
12-22
Other DataInput methods
• public abstract void readFully(byte[] buf) throws
IOException
• public abstract void readFully(byte[] buf,int off,int len)
throws IOException
• public abstract int skipBytes(int n) throws IOException
• public abstract String readLine() throws IOException
• public abstract int readUnsignedByte() throws IOException
• public abstract int readUnsignedShort(byte[] buf) throws
IOException
The DataInput interface handles end-of –file by throwing an
EOFException when it occurs. EOFException is an extended class of
IOException
Programming in Java
12-23
Other DataOutput methods
12-24
•The DataOutput interface supports signatures equivalent to
the three forms of write in OutputStream
• public abstract void writeBytes(String s) throws IOException
• public abstract void writeChars(String s) throws
IOException
DataInputStream/DataOutputStream:
• For each Data interface, there is a corresponding Data stream
• Each Data class is an extension of its Filter class, so Data
streams can be used to filter other streams
• Constructor parameters: InputStream in/OutputStream out
Programming in Java
Example
int account ;
String name;
double balance;
try { input=new DataInputStream(
new FileInputStream(“client.dat”))
} catch (IOException e) {
System.err.println(“Fail to open the file”+e.toString());
System.exit(1); }
try { account = input.readInt();
name = input.readUTF();
balance = input.readDouble();
} catch (EOFException eof) { …}
catch (IOException e) {…}
Programming in Java
12-25
Buffered Streams
• The BufferedInputStream/BufferedOutputStream classes
support objects that buffer their data to avoid every read or
write going directly to the next stream
• When a buffered stream is created, its buffer size can be
specified explicitly(InputStream in, int size),or it can use a
default size[32b] (InputStream in)
• BufferedOutputStream behaves similar to OutputStream
• Example
OutputStream bufferedFile(String path) //为文件提供缓冲流
throws IOException
{ OutputStream out=new FileOutputStream(path);
return new BufferedOutputStream(out);
}
Programming in Java
12-26
PrintStream
• PrintStream is used every time a print or println method
invocation appears in a program
• It provides print and println methods for the following
types:char,int, float,object,boolean, char[],long, double, String
• Two Constructors: (OutputStream out) 、
(OutputStream out, boolean autoflush)
If the autoflush boolean is true,writing a new line character
‘\n’ invokes flush
• The print(String) and print(char[]) methods are
synchronized. All the other print and println methods are
written in terms of these two methods,so printing on a
PrintStream object is thread-safe
Programming in Java
12-27
PushbackInputStream
• A PushbackInputStream provides single-character
pushback
• The pushback buffer is a protected int field named
pushBack. A subclass could provoide a different way to
modify this character. A value of –1 means the pushback
buffer is empty. Any other value means that the
PushBack.read method returns pushBack as the first byte
of input
• Constractor parameter: (InputStream in)
• unread(int ch)return the int which represent a char into
input stream
•Example:
This example PushbackInputStream to find the longest
sequence of any single byte in its input
Programming in Java
12-28
Example(1)
import java.io.*;
class SequenceCount{
public static void main(String[] args){
try{PushbackInputstream in=new …(System.in);
int max=0;
//所找到的长序列
int maxB=-1; //构成该序列的字节
int b;
//当前输入字节
do{
int cnt;
int bl=in.read(); //序列中的第一个字节
for(cnt=1;(b=in.read())==b1;cnt++)
continue;
Programming in Java
12-29
Example(2)
if (cnt>max){
max=cnt; //记下长度
maxB=b1; //记下字节的值
}
in.unread(b); //回送下个序列的开始字节
}while(b!=-1); //读到输入的结束
System.out.println(max+”bytes of”+maxB);
}catch(IOException e){
System.out.println(e);
System.exit(1);
} //当到达一个序列结尾时,下个序列的第一个字
} // 节实际已经被读入。用unread将该字节回送
}
Programming in Java
12-30
LineNumberInputStream
•The LineNumberInputStream class provides an object to
keep track of line numbers while reading input
• The getLineNumber method returns the current line
number. Line numbering starts at 1
•The current line number can be set with setLineNumber.
This is useful when multiple input streams are treated as
one input stream,but line numbers are needed relative to
each stream
• Example:This program prints the line number where the
first instance of a particular character is found in a file
•To ensure that the current line number from Sysytem.in:
LineNumberInputStream
lnum = new LineNumberInputStream(System.in);
System.in = lnum;
Programming in Java
12-31
Other Byte I/O Streams(1)
• The java.io package defines many
classes.Extensions of InputStream include the
following:
– ByteArrayInputStream:lets you read an array of bytes as
though it is an InpputStream object
– SequenceInputStream:provides a mechanism for
concatenating the data from two or more InputStream
objects into a single,seamless stream
– PipedInputStream:implements half a pipe and is
especially useful for communication between threads
– StringBufferInputStream: reads from a String instead of
a byte array(the same as ByteArrayInputSteam )
Programming in Java
12-34
Other Byte I/O Streams(2)
12-35
• Extensions of OutputStream include the following:
– ByteArrayOutputStream:sends its output into an object of
type byte[]
– PipedOutputStream:is the complementary class to
PipedInputStream. Together, these two classes comprise a
pipe that you can use for communication between
threads
Programming in Java
ByteArray Streams
12-36
ByteArray Streams uses a byte array as its input/output source
(1) ByteArrayInputStream
• public ByteArrayInputStream(byte[] buf)
•
public ByteArrayInputStream(byte[] buf,int offset,int len)
•
reset(): 指针移到流的开始
(2) ByteArrayOutputStream
• public ByteArrayOutputStream() (32 bytes)
• public ByteArrayOutputStream(int size)
• public synchronized byte[] toByteArray()
• public int size()
• public String toString(int hiByte)
Programming in Java
Example
String tmp = “abcdefghijklmnopqrstuvwxyz”;
byte b[] = new byte [tmp.length())];
tmp.getBytes(0,tmp.length(),b,0);
ByteArrayInputStream n1=new ByteArrayInputStream(b);
… n2=new ByteArrayInputStream(b,0,3); // abc
for (int i=0; i<2; i++) { // 打印大小写字母表
while ((c=n1.read())!=-1)
if (i==0) System.out.print((char)c);
else System.out.print(Character.toUpperCase(c));
System.out.println();
input.reset();
}//将读指针移到字节数组的开始
Programming in Java
12-37
SequenceInputStream
• The SequenceInputStream class creates a single input
stream from reading one or more input streams,reading the
first until last
• Two constructors:one for the common case of two input
streams;the other for any arbitrary number of input
streams using the Enumeration abstraction
Programming in Java
12-38
Example(1)
import java.io.*;
import java.util.Vector;
class Sum{
public static void main(String[] args){
InputStream in;
if (args.length==0){
in=System.in;
}else{
InputStream stringIn;
Vector inputs=new Vector(args.length);
for(int i=0;i<args.length;i++){
String arg=args[i]+“ ”;
stringIn = new StringBufferInputStream(arg);
inputs.addElement(stringIn);
}
Programming in Java
12-39
Example(2)
in=new SequenceInputStream(inputs.elements());
}
try{
double total=sumStream(in);
System.out.println(“The sum is”+total);
}catch(IOException e){
System.out.println(e);
System.exit(-1);
}
}
//...
}
Programming in Java
12-40
Piped Streams
• Bytes written on the input stream of a pair are those
read on the output
• Piped streams are thread-safe: one for reading and one
for writing
• Writing on one end of the pipe blocks the thread when
the pipe files up
• If the writer and reader are the same thread, that thread
blocks permanently
• Example:
This example creates a new thread to read from the output
of some data generator object that writes its output onto
an OutputStream object
Programming in Java
12-41
Example
class Pipe{
public static void main(String[] args){
try{
PipedOutputStream out=new PipedOutputStream();
PipedInputStream in=new PipedInputStream(out);
// 数据产生器将结果写入给定的输出流中
DataGenerator data=new DataGenerator(out);
data.setPriority(Thread.MIN_PRIORITY);
data.start(); int ch;
while((ch=in.read())!=-1)
System.out.print((char)ch);
System.out.println();
}catch(IOException e){
System.out.println(“Exception:”+e); } }
}
Programming in Java
12-42
StringBufferInputStream
• It provides a single constructor that is the string from
which to read.Each character in the string is treated as a
byte
• Note that StringBufferInputStream operats on String
object, not StringBuffer objects
• There is no StringBufferOutputStream. A similar effect
can be obtain by using the toString method on
ByteArrayInputSteam
Programming in Java
12-43
Example
class Factor {
public static void main(String[] args) {
if (args.length = = 0) {
factorNumbers(System.in);
}
else {
InputStream in;
for (int i = 0; i < args.length; i ++) {
in = new StringBufferInputStream(args[i]);
factorNumbers(in);
}
}
} //…
}
Programming in Java
12-44
File I/O Basics
12-45
• Programming stream I/O to and from files is much
like that to and from the console
• Difference exits between files and the standard
console I/O objects:
– Before you can use a file,you must associate the file with
a FileInputStream or FileOutputStream object
– If you want to access the data in a file in random-access
order, you must open it as a RandomAccessFile
– In a network environment, the default security
restrictions do not let applets do any file I/O on the client
workstation
Programming in Java
File Streams
(1) FileInputStream
•
•
Constructor
— A constructor that takes a String that is the name of
the file
— A constructor that takes a File that refers to the file
— A constructor that takes a FileDescriptor object
Methods: overwrite six methods of InputStream
InputStream f0 = new FileInputStream(“a.bat”);
File f = new File(“a.bat”);
InputStream f1 = new FileInputStream(f);
(2) FileOutputStream
• Open read-only file,signals an exception
• Open a file which created already,its content will be lost
Programming in Java
12-46
File InputStreams Example(1)
import java.io.*; import java.util.*
class FileInputDemo {
public static void main(String args[]) throws
Exception{
int size;
InputStream f1=new FileInputStream(“file.htm”);
size=f1.available(); // total size
// Read the first 1/4 by read()
for (int i=0; i<size/4; i++)
System.out.print((char)f1.read());
System.out.println(“Still available: ”+f1.available());
Programming in Java
12-47
File InputStreams Example(2)
// Read the next 1/8 by read(b[])
byte b[] = new byte[size/8];
if (f1.read(b)!=b.length)
System.err.println(“Something bad happened!”);
System.out.println(“Still available: ”+f1.available());
// Skip another 1/4: skip()
f1.skip(size/4);
System.out.println(“Still available: ”+f1.available());
f1.close();
}
}
Programming in Java
12-48
File OutputStreams Example(1)
import java.io.*
class FileOutputDemo {
public static byte getInput()[] throws Exception {
byte buffer[] = new byte[12];
for (int i=0;i<12;i++)
buffer[i]=(byte) System.in.read();
return buffer;
}
Programming in Java
12-49
File OutputStreams Example(2)
public static void main(String args[]) throws Exception
{
byte buf[]=getInput();
OutputStream f0=new FileOutputStream(“file1.txt”);
OutputStream f1=new FileOutputStream(“file2.txt”);
OutputStream f2=new FileOutputStream(“file3.txt”);
for (int i=0;i<12;i+=2) f0.write(buf[i]);
f0.close();
f1.write(buf);
f1.close();
f2.write(buf,12/4, 12/2);
f2.close(); }
}
Programming in Java
12-50
The File Class(1)
12-51
The File class provides several common manipulations that
are useful with filenames. It provides methods to separate
pathnames into subcomponents, and for querying the file
system about the file a pathname refers to
(1) Constructors:
•
public File(String path) :Creates a File object to manipulate
the specified path.This method throws a NullPointerException if
the path parameter is null
•
•
public File(String dirName,String name)
File(dirName + File.separator +name)
public File(File fileDir,String name)
File(fileDir.getPath(), name)
Example: File f1=new File(“/”);
File f2=new File(“/”,”autoexec.bat”);
File f3=new File(f1,”autoexec.bat”);
Programming in Java
The File Class(2)
12-52
(2) Methods
• get: retrieve information about components of a File object’s
pathname
getName()、getPath、getAbsolutePath()、getParent()
• exists: returns true if the file exists in the file system
• canRead: returns true if the file exists and can be read
• canWrite: returns true if the file exists and can be written
• isFile: returns true if the file is a normal file
• isDirectory: returns true if the file is a directory
• isAbsolute: returns true if the path is an absolute pathname
• public long lastModified(): returns the last modification time
Programming in Java
The File Class(3)
• public long length(): returns the file length in bytes
• public boolean mkdir(): Creates a directory, returning
true on success
• public boolean mkdirs(): Creates all directories in this
path,returning true if all were created
• public boolean renameTo(File new_name) : Renames a file,
returning true if the rename succeeded
• public boolean delete() : Deletes the file or directory
named in this File object, returning true if the deletion
succeeded
• public String[] list(): Lists all files in a directory except the
equivalent of “.”and “..”
Programming in Java
12-53
The File Class(4)
• public String[] list(FilenameFilter filter) :Uses the
specified filter to list files in a directory
(3) Note
• equals:true if two file objects have the same path , not if
they refer to the same underlying file system object
• Files are created using FileOutputStream objects or
RandomAccessFile objects, not using File objects
• The character File.pathSeparatorChar and the string
File.pathSeparator represent the character that separates
file or directory names in a search path
• The path of the file is a protected String field named
path.Classes extending File can directly access or modify it
as needed
Programming in Java
12-54
Example1
import java.io.*;
public class CopyBytes {
public static void main(String[] args) throws IOException
{
if(args.length != 2)
throw new RuntimeException(“Usage:CopyBytes
<src> <dst>”);
File inputFile = new File(args[0]);
File outputFile = new File(args[1]);
FileInputStream in = new FileInputStream(inputFile);
FileOutputStream out = new
FileOutputStream(outputFile);
int c;
while ((c = in.read()) != -1) out.write(c);
in.close();
out.close(); }
}
Programming in Java
12-55
Example2
import java.io.*;
public class FileOperation {
public static void main(String[] args)
{try{
BufferedReader in = new BufferedReader(new
InputStreamReader(System.in));
String sdir = “c:\\temp”;
String sfile;
File Fdir1 = new File(sdir);\\创建目录c:\temp
if (Fdir1.exits() && Fidir1.isDirectory()) \\目录存在
{System.out.println(“Directory” + sdir + “exits.” );
for (int I=0; I<Fdir1.list().length; I++) \\列出目录内容
System.out.println((Fdir1.list())[i] );
File Fdir2 = new File(“c:\\temp\\temp”);
Programming in Java
12-56
Example2
12-57
if (!Fdir2.exits())
Fdir2.mkdir(); \\目录不在则创建之
System.out.println();
System.out.println(“Now the new list after create a new dir:”);
for (int I=0; I<Fdir1.list().length; I++) \\检查目录是否已建立
System.out.println((Fdir1.list())[i] );}
System.out.println(“Enter a file name in this directory:”);
sfile = in.readLine();
File Ffile = new File(Fdir1, sfile);
if (Ffile.isFile()) \\若此File对象代表文件
{System.out.println(“File” +Ffile.getName() +”in Path”
+Ffile.getPath() + “is” +Ffile.getlength() +”in length.”); }
}catch()…
Programming in Java
RandomAccessFile(1)
•
The “random access” referred to in the name of the class is
the ability to set the read/write file pointer to any position
in the file,and perform the operation
•
You cannot use a RandomAccessFile where either an
InputStream or OutputStream object required,but it
supports methods of the same names and signatures as
their read and write invocations
•
RandomAccessFile implements both the DataInput and
DataOutput interface, so it can be used to read and write
bulit-in Java data types
(1) Constructors:
•
public RandomAccessFile(String name,String mode)
throws IOException
Programming in Java
12-58
RandomAccessFile(2)
• public RandomAccessFile(File file,String mode) throws
IOException
• public RandomAccessFile(FileDescriptor fd) throws
IOException
(2) Methods
•
public long getFilePointer() throw IOExcepton
Returns the current location of the file pointer(in bytes)
from the beginning of the file
•
public void seek(long pos) throw IOException
Sets the file pointer to the specified position in number of
bytes from the beginning of the file
•
public long length() throws IOException
Programming in Java
12-59
Characters Streams
• Reader and Writer are the abstract
superclasses for character streams in java.io
Reader provides the API and partial
implementation for readers
--streams that read 16-bit characters
Writer provides the API and partial
implementation for writers
--streams that write 16-bit characters
Programming in Java
12-60
Character Stream Classes
CharArrayReader
InputStreamReader
FilterReader
FileReader
PushBackReader
StringReader
Reader
PipedReader
BufferedReader
Object
LineNumberReader
BufferedWriter
CharArrayWriter
OutputStreamWriter
Writer
FilterWriter
PipedWriter
PrintWriter
StringWriter
StreamTokenizer
Programming in Java
FileWriter
12-61
Subclasses of Reader and Writer
Object
Reader
Writer
BufferedWriter
BufferedReader
CharArrayWriter LineNumberReader
CharArrayReader
FilterWriter
FilterReader
OutputStreamWriter
PpushbackReader
FileWriter
InputStreamReader
PipedWriter
FileReader
PrintWriter
PipedReader
StringWriter
StringReader
Programming in Java
12-62
The corresponding input/output streams(1)
Reader
InputStream
BufferedReader
LineNumberReader
BufferedInputStream
LineNumberStream
CharArrayReader
ByteArrayInputStream
InputStreamReader
(none)
FileReader
FilterReader
PushbackReader
FileInputStream
FilterInputStream
PushbackInputStream
PipedReader
PipedInputStream
StingReader
StringBufferInputStream
Programming in Java
12-63
The corresponding input/output streams(2)
Writer
OutputStream
BufferedWriter
BufferedOutputStream
CharArrayWriter
ByteArrayOutputStream
OutputStreamWriter
(none)
FileWriter
FileOutputStream
FilterWriter
FilterOutputStream
PrintWriter
PrintStream
PipedWriter
PipedOutputStream
StingWriter
(none)
Programming in Java
12-64
StreamTokenizer(1)
12-65
(1) function
•
Tokenizing input data is a common application,and the
java.io package provides a StreamTokenizer class for simple
tokenization problems
•
It deals only with the lower 8 bits of Unicode(’\u0000’‘\u00FF’ )
•
A stream is tokenized by creatinga StreamTokenizer with an
InputStream object as its source, and then setting
parameter for the scan. A scanner loop invokes nextToken,
which returns the token type of the next token in the
stream
Programming in Java
StreamTokenizer(2)
(2) Token types:
•“ordinary”characters
•“special” characters
•TT_WORD(-3) :A word was scanned
• TT_NUMBER(-2) :A number was scanned
• TT_EOL(‘\n’):An end-of-line was found
• TT_EOF(-1) : The end-of-file was reached
static double sumStream(Inputstream in)
throws IOException{
StreamTokenizer nums = new StreamTokenizer(in);
double result = 0.0;
while(nums.nextToken() ==StreamTokenizer.TT_NUMBER)
result += nums.nval;
return result; }
Programming in Java
12-66
StreamTokenizer(3)
(3) Method
• public void wordChars(int low,int hi)
• public void whitespaceChars(int low,int hi)
• public void ordinaryChar(int ch)
• public void ordinaryChars(int low,int hi)
• public void commentChar(int ch)
• public void quoteChar(int ch)
• public void parseNumbers()
• public void resetSyntax()
• public void eolIsSignificant(boolean flag)
• public void slashStarComments(boolean flag)
• public void slashSlashComments(boolean flag)
• public void lowerCaseMode(boolean flag)
• public void pushback()
• public int lineno()
• public String toString()
Programming in Java
12-67
Example(1)
Import java.io.*;
Public class IODemo
Public static void main (String[] args) {
try { //1.Reading input by lines:
if (args.length = = 0) {
BufferedReader stdin = new BufferedReader(
new InputStreamReader(System.in)) ;
System.out.print(“Enter a line:”);
System.out.println(stdin.readLine());
stdin.close(); }
else
BufferedReader in =
new BufferedReader(new FileReader(args[0])) ;
String s, s2 = new String();
While ((s = in.readLine()) != null )
s2 += s + “\n”;
in.close();
Programming in Java
12-68
Example(2)
//2. Input from memory
StringReader in2 = new StringReader (s2);
int c;
While ((c = in2.read()) != -1)
System.out.print((Char)c);
Note: read() returns next byte as an int, so you must cast it as a char
Programming in Java
12-69
Example(3)
//3. Formatted memory input
try {
DataInputStream in3 =
new DataInputStream (
new StringBufferInputStram(s2));
while (true)
System.out.print((char)in3.readByte());
} catch (EOFException e) {
System.out.println(“End of stram”); }
Programming in Java
12-70
Example(4)
try { //4. Line numbering &file output
LineNumberReader li =
new LineNumberReader(
new StringReader(s2));
BufferedRader in4 = new BufferedRader(li);
PrintWriter out1 =
new PrintWriter(new BufferedWriter(
new FileWriter (“IODemo.out”)));
while ((s = in4.readLine()) != null)
out1.println (“Line”+ li.getLineNumber()+s);
out1.close();
} catch (EOFexception e) {
System.out.println(“End of stream”);}
Programming in Java
12-71
Example(5)
//5. Storing & recovering data
try {
DataOutputStream out2 =
new DataOutputStream(
new BufferedOutputStream (“Data.txt”)));
out2.writeDouble(3.14159);
out2.writeBytes(“That was pi”); out2.close();
DataInputStream in5 =
new DataInputStream (
new BufferedInputStream(
new FileInputStream(“Data.txt”)));
Programming in Java
12-72
Example(6)
BufferedReader in5br =
new BufferedReader (
new InputStreamReader(in5));
// Must use DataInputStream for data:
System.out.println(in5.readDouble());
//Can now use the “proper” readLine())
System.out.println(in5br.readLine());
} catch (EOFException e) {
System.out.println (“End of Stream”);
}
Programming in Java
12-73
Example(7)
//6. Reading and Writing random access file
RandomAccessFile rf =
new RandomAccessFile(“rtest.dat”, “rw”);
for (int i = 0; i <10 ; i++)
rf.writeDouble(i*1.414);
rf.close();
rf = new RandomAccessFile(“rtest.dat”, “rw”);
rf.seek(5*8);
rf.writeDouble(47.0001);
rf.close();
rf = new RandomAccessFile(“rtest.dat”, “r”);
Programming in Java
12-74
Example(8)
for (int i = 0; i <10 ; i++)
System.out.println(
“Value” + i + “:” +rf.readDouble());
rf.close();
} catch (FileNotFoundException e) {
System.out.println (
“File Not Found:” + args[1]);
} catch (IOException e) {
System.out.println(“IO Exception”);}
}
}
Programming in Java
12-75
Homework
1.实现一个常用的词统计程序wc(统计任何输入流的字
符数、行数和词数)。程序有两种状态,如果没有文
件名作参数,程序就使用标准的输入流,如果有一个
或多个文件,程序就依次进行统计。
•
用FileInputStream实现wc程序
•
用PushbackInputStream实现wc程序
2. 两个线程,一个是读者,一个是写者,读者取写者所
写的内容,双方约定以“.”为信息的结束符。用管道
I/O类实现该程序。
Programming in Java
12-76