Вы находитесь на странице: 1из 36

Java

15. java.io
20 2003
:
( Sun ) <vyazovick@itc.mipt.ru>
( Sun ) < gene@itc.mipt.ru>
Copyright 2003 Sun , , .

Java ,
.
, , ,
.. (
InputStream OutputStream) (Reader Writer).
java.io ,
.
.

Rendered by www.RenderX.com

ii

15. java.io..................................................................................................... 1
1. /. (stream)..........................................................1
1.1. InputStream OutputStream...................................................................... 3
1.2. - .................................................................... 5
1.2.1. ByteArrayInputStream ByteArrayOutputStream ............................5
1.2.2. FileInputStream FileOutputStream ................................................6
1.2.3. PipedInputStream PipedOutputStream ...................................................... 8
1.2.4. StringBufferInputStream................................................................................. 9
1.2.5. SequenceInputStream ...................................................................................9
1.3. FilterInputStreeam FilterOutputStream. ....................... 11
1.3.1. BufferedInputStream BufferedOutputStream ........................................... 11
1.3.2. LineNumberInputStream ............................................................................. 13
1.3.3. PushBackInputStream .................................................................................13
1.3.4. PrintStream...................................................................................................14
1.3.5. DataInputStream DataOutputStream ....................................................... 14
2. Serialization.....................................................................................................................15
2.1. ..................................................................................................... 22
3. Reader Writer. .......................................................................23
4. StreamTokenizer.................................................................................................. 26
5. .......................................................................................27
5.1. File...............................................................................................................27
5.2. RandomAccessFile......................................................................................29
6. .................................................................................................................... 29
7. ...................................................................................................30

Java

Rendered by www.RenderX.com

. 1 34

15. java.io
.
1. /. (stream)......................................................... 1
1.1. InputStream OutputStream............................................................................ 3
1.2. - .......................................................................... 5
1.2.1. ByteArrayInputStream ByteArrayOutputStream ................................. 5
1.2.2. FileInputStream FileOutputStream ..................................................... 6
1.2.3. PipedInputStream PipedOutputStream ............................................................ 8
1.2.4. StringBufferInputStream.......................................................................................9
1.2.5. SequenceInputStream .........................................................................................9
1.3. FilterInputStreeam FilterOutputStream. ............................. 11
1.3.1. BufferedInputStream BufferedOutputStream ................................................. 11
1.3.2. LineNumberInputStream ................................................................................... 13
1.3.3. PushBackInputStream .......................................................................................13
1.3.4. PrintStream........................................................................................................ 14
1.3.5. DataInputStream DataOutputStream ............................................................. 14

2. Serialization.................................................................................................................... 15
2.1. ........................................................................................................... 22

3. Reader Writer. ...................................................................... 23


4. StreamTokenizer................................................................................................. 26
5. ...................................................................................... 27
5.1. File.....................................................................................................................27
5.2. RandomAccessFile............................................................................................29

6. ................................................................................................................... 29
7. .................................................................................................. 30

1. /. (stream)
. ,
, -
, .

. , ,
, -
Java

Rendered by www.RenderX.com

. 2 34

/. (stream)

. , , ,
- , , ()
.. - , ,
, () .. ,

.
, ,
- /. Java java.io (input/output).
/
, .
,
( 4 ),
.
(, HTML ),
( ).
.
Java /
(stream). ,
. ,
- , - () .
stream ,
,
/.
Java .
java.io.
. -
, .
.
"" , , ,
0 1 ( ,
; , 1
, 0 - ).
, 8 . , , 1 ,
0 28-1=255, , , -128 +127.
byte Java , .
,
. , java.io
, .
, - double , ,
. ,
(.. ) -
. ,
- ,
.

Java

Rendered by www.RenderX.com

InputStream OutputStream

. 3 34

/. ,
.
InputStream:

- OutputStream:

1.1. InputStream OutputStream


InputStream - , .. . ,
.
, InputStream.
read() ( ).
, , , -.
,
int. ,
0 255 (
int 4
). ,
-128 +127 byte Java.
, ,
-1.
- - ,
java.io.IOException. Exception, ..
. , ,
, , , ,
Java

Rendered by www.RenderX.com

. 4 34

/. (stream)

. , ,
.
read() - ,
-.
, -
. read(),
byte[].
read() ( ), .
, , .
, ,
. , , ()
. int, ,
. , 0
.
, ,
read(), byte[], int
. - , ,
- , . ,
int - offset () length (),
java.io.
read(), ,
. , ,
, . ,
, - read()
"".
, - available().
int, ,
. , ,
, .
available() - , ,
.
, .
close(). ,
.
, InputStream - , OutputStream
- .
OutputStream, , write() -
int, byte[], byte[], int-.
void, .
write(int) , - .
int,
byte - 8 . 24
. java.io.IOException,
, , , -.

Java

Rendered by www.RenderX.com

. 5 34

, write()
. , - byte[],
int- - . ,
- , ,
+ -
IndexOutOfBoundsException.
, ,
. , - ,
10 , 200 . 200
,
2000 .
( )
. , , ,
flush(), OutputStream.
, - ,
.
, .
close(). , ,
.
. OutputStream
close() .
, InputStream OutputStream
. . -
, .
, , , , .. , ,
, , .

1.2. -
1.2.1. ByteArrayInputStream ByteArrayOutputStream
, - , ,
. ByteArrayInputStream ,
. ,
byte[]. , read(),
. :
byte[] bytes = {1,-1,0};
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
int readedInt = in.read(); // readedInt=1
System.out.println("first element read is: " +readedInt);
readedInt = in.read(); // readedInt=255. (byte)readedInt
-1
System.out.println("second element read is: " +readedInt);
readedInt = in.read(); // readedInt=0
System.out.println("third element read is: " +readedInt);

Java

Rendered by www.RenderX.com

. 6 34

/. (stream)

, :
first element read is: 1
second element read is: 255
third element read is: 0

read() bytes,
ByteArrayInputStream. -1,
. 255. , ,
, read byte, int -
( ). , -1
11111111 , , ,
24- , 255( ).
byte, .
, , ByteArrayOutputStream.
byte[], ,
write(). ,
toByteArray(). :
ByteArrayOutputStream out = new ByteArrayOutputStream();
out.write(10);
out.write(11);
byte[] bytes = out.toByteArray();

bytes : 10 11.
ByteArrayInputStream ByteArrayOutputStream
, , . ,
.
, ,
, , - .

1.2.2. FileInputStream FileOutputStream


FileInputStream .
,
. ,
,
. ,
,
java.io.FileNotFoundException.
, , read(),
.
FileOutputStream.
, , ,
. ,
, FileOutputStream
. , write(),
Java

Rendered by www.RenderX.com

. 7 34

. close(),
, . :
byte[] bytesToWrite = {1, 2, 3};
byte[] bytesReaded = new byte[10];
String fileName = "d:\\test.txt";
try {
//
FileOutputStream outFile = new FileOutputStream(fileName);
System.out.println(" ");
//
outFile.write(bytesToWrite);
System.out.println(": " + bytesToWrite.length + " ");
//
outFile.close();
System.out.println(" ");
//
FileInputStream inFile = new FileInputStream(fileName);
System.out.println(" ");
// ,
int bytesAvailable = inFile.available();
System.out.println(" : " + bytesAvailable + " ");
//
int count = inFile.read(bytesReaded,0,bytesAvailable);
System.out.println(": " + count + " ");
inFile.close();
System.out.println(" ");
} catch (FileNotFoundException e) {
System.out.println(" : " + fileName);
} catch (IOException e) {
System.out.println(" /: " + e.toString());
}

FileInputStream available() ,
, .
,
- available() ,
. , ,
,
.

.
finally .
} finally {
try{inFile.close();}catch(IOException e){};
}

Java

Rendered by www.RenderX.com

. 8 34

/. (stream)

, ,
.

1.2.3. PipedInputStream PipedOutputStream


PipedInputStream PipedOutputStream ,
- PipedInputStream
PipedOutputStream. ,
.
: PipedInputStream PipedOutputStream, . PipedOutputStream
PipedInputStream .
- , PipedOutputStream ,
PipedInputStream.
connect()
PipedStream, .
PipedInputStream PipedOutputStream.
try {
int countRead = 0;
byte[] toRead = new byte[100];
PipedInputStream pipeIn = new PipedInputStream();
PipedOutputStream pipeOut = new PipedOutputStream(pipeIn);
// ,
while(countRead<toRead.length){
//
for(int i=0; i<(Math.random()*10); i++){
pipeOut.write((byte)(Math.random()*127));
}
// ,
// .
int willRead = pipeIn.available();
if(willRead+countRead>toRead.length)
//
willRead = toRead.length-countRead;
countRead += pipeIn.read(toRead, countRead, willRead);
}
} catch (IOException e) {
pr("Impossible IOException occur: ");
e.printStackTrace();
}

,
. ,
, (
- Thread, Stream Thread - ),

PipedStream. PipedInputStream
Java

Rendered by www.RenderX.com

. 9 34

PipedOutputStream, Thread.
, :
// inStream - PipedInputStream
try{
while(true){
byte[] readedBytes = null;
synchronized(inStream){
int bytesAvailable = inStream.available();
readedBytes = new byte[bytesAvailable];
inStream.read(readedBytes);
}
// do some work with readedBytes
//
}catch(IOException e){
/* IOException , inStream
PipedOutputStream ,
inStream */
System.out.println(" inStream ");
}

inStream ,
synchronized(inStream){} ,
inStream.available() inStream.read(),
inStream. inStream.read(readedBytes)
, , - .

1.2.4. StringBufferInputStream
StringBufferInputStream - ,
.
.
- , - String byte,
StringBufferInputStream. ,
, ,
. StringBufferInputStream
String. , read(),
String.
- 8 (
char 2- ).

1.2.5. SequenceInputStream
SequenceInputStream .
.
- , ,
. SequenceInputStream ,
, .

Java

Rendered by www.RenderX.com

. 10 34

/. (stream)


InputStream - Enumeration .
read(), SequenceInputStream .
( -1),
close(), .
, ,
. , ,
, SequenceInputStream -1,
, . SequenceInputStream
close() , . close()
SequenceeInputStream ,
.
:
FileInputStream inFile1 = null;
FileInputStream inFile2 = null;
SequenceInputStream sequenceStream = null;
FileOutputStream outFile = null;
try {
inFile1 = new FileInputStream("file1.txt");
inFile2 = new FileInputStream("file2.txt");
sequenceStream = new SequenceInputStream(inFile1, inFile2);
outFile = new FileOutputStream("file3.txt");
int readedByte = sequenceStream.read();
while(readedByte!=-1){
outFile.write(readedByte);
readedByte = sequenceStream.read();
}
} catch (IOException e) {
System.out.println("IOException: " + e.toString());
} finally {
try{sequenceStream.close();}catch(IOException e){};
try{outFile.close();}catch(IOException e){};
}

file3.txt
file1.txt file2.txt - file1.txt file2.txt.
finally. , close() IOException,
try-catch . try-catch
close() - ,
.
inFile1 inFile2 -
sequnceStream - ,
sequencecStream close().
SequenceInputStream :
Enumeration, , Enumeration
SequenceInputStream:

Java

Rendered by www.RenderX.com

FilterInputStreeam FilterOutputStream. .

. 11 34

Vector vector = new Vector();


vector.add(new StringBufferInputStream("Begin file1\n"));
vector.add(new FileInputStream("file1.txt"));
vector.add(new StringBufferInputStream("\nEnd of file1, begin file2\n"));
vector.add(new FileInputStream("file2.txt"));
vector.add(new StringBufferInputStream("\nEnd of file2"));
Enumeration enum = vector.elements();
sequenceStream = new SequenceInputStream(enum);

sequenceeStream
, file3.txt file1.txt file2.txt
- , file1.txt file2.txt
file3.txt.

1.3. FilterInputStreeam FilterOutputStream. .


, / -
, , ,
.
. ,
, . (
.) -
. ,
- /. java.io .
-, , ,
.
java.io / FilterInputStream ( ) FilterOutputStream ( ).
/ - InputStream OutputStream
.
InputStream protected.
. ( ),
.
.
- ,
, :
, ,
.

1.3.1. BufferedInputStream BufferedOutputStream


, ,
. BuffereInputStream
BufferedOutputStream.
BufferedInputStream - ,
. , ( read())
( skip()), ,
Java

Rendered by www.RenderX.com

. 12 34

/. (stream)

. BufferedInputStream
mark() reset(). InputStream,
IOException. mark()
reset() , ,
mark(), ,
.
BufferedOutputStream - ,
/ .
.
, , ,
.
- flush().
( close()).
, .

.
try {
String fileName = "d:\\file1";
InputStream inStream = null;
OutputStream outStream = null;
//
long timeStart = System.currentTimeMillis();
outStream = new FileOutputStream(fileName);
outStream = new BufferedOutputStream(outStream);
for(int i=1000000; --i>=0;){
outStream.write(i);
}
long time = System.currentTimeMillis() - timeStart;
System.out.println("Writing durates: " + time + " millisec");
outStream.close();
//
timeStart = System.currentTimeMillis();
inStream = new FileInputStream(fileName);
while(inStream.read()!=-1){
}
time = System.currentTimeMillis() - timeStart;
inStream.close();
System.out.println("Direct read durates " + (time) + " millisec");
timeStart = System.currentTimeMillis();
inStream = new FileInputStream(fileName);
inStream = new BufferedInputStream(inStream);
while(inStream.read()!=-1){
}
time = System.currentTimeMillis() - timeStart;
inStream.close();
System.out.println("Buffered read durates " + (time) + " millisec");

Java

Rendered by www.RenderX.com

FilterInputStreeam FilterOutputStream. .

. 13 34

} catch (IOException e) {
pr("IOException: " + e.toString());
e.printStackTrace();
}

, , :
Writing durates: 359 millisec
Direct read durates 6546 millisec
Buffered read durates 250 millisec

,
, .
10 (!) ,
.
, ,
, BufferedOutputStream.
.
BufferedInputStream BufferedOutputStream
, .

. , - LineNumberInputStream deprecated
jdk 1.1, .

1.3.2. LineNumberInputStream
InputStream , ,
. ,
getLineNumber().
, setLineNumber(int lineNumber).
, '\n' '\r'
'\r\n' . OutputFilter
- .

1.3.3. PushBackInputStream
.
unread(). ,
- ,
. ,
, .
, .
OutputFilter - .
deprecated,
, .
, out err
System , ,
.

Java

Rendered by www.RenderX.com

. 14 34

/. (stream)

1.3.4. PrintStream
. PrintStream
print(), java Object.

String.valueOf(), . ,
, . ,
, print .
, ,
. PrintStream Unicode.
Writer`.
InputFilter - .
, - .
.

.

1.3.5. DataInputStream DataOutputStream


byte.
java, DataInput
DataOutput, - - DataInputStream
DataOutputStream. /
, .1 .2.
DataInput DataOutput , DataInputStream DataOutputStream, ,
. byte .
,
- , ,
. , , , int long,
short - -
,
- , .
:
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
DataOutputStream outData = new DataOutputStream(out);
outData.writeByte(128); // it would write -128, as casted to byte
outData.writeInt(128);
outData.writeLong(128);
outData.writeDouble(128);
outData.close();
byte[] bytes = out.toByteArray();
InputStream in = new ByteArrayInputStream(bytes);
DataInputStream inData = new DataInputStream(in);
System.out.println("Read data in order it was writen: ");
System.out.println("readByte: " + inData.readByte());

Java

Rendered by www.RenderX.com

FilterInputStreeam FilterOutputStream. .

. 15 34

System.out.println("readInt: " + inData.readInt());


System.out.println("readLong: " + inData.readLong());
System.out.println("readDouble: " + inData.readDouble());
inData.close();
System.out.println("read the same data in other order (first byte is
skipped):");
in = new ByteArrayInputStream(bytes);
inData = new DataInputStream(in);
System.out.println("readInt: " + inData.readInt());
System.out.println("readDouble: " + inData.readDouble());
System.out.println("readLong: " + inData.readLong());
inData.close();
} catch (Exception e) {
System.out.println("Impossible IOException occurs: " + e.toString());
e.printStackTrace();
}

DataInput DataOutput /
Java.
ObjectInput ObjectOutput . java.io
- ObjectInputStream ObkectOutputStream.

- ,
..
(Serialization) , , -
- .

2. Serialization
java - .
, ,
java.io.Serializable(
, , ).
java.io.Serializable .
, .
, ,
java.io.NotSerializableException

, , ,
,
( , ),

, .
Java - ,
Windows, ,
Unix, .

Java

Rendered by www.RenderX.com

. 16 34

Serialization

java.io ObjectInput, ObjectOutput


ObjectInputStream ObjectOutputStream .
OutputStream,
ObjectOutputStream. writeObject()
. :
ByteArrayOutputStream os = new ByteArrayOutputStream();
Object objSave = new Integer(1);
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(objSave);

, objSave,

byte[] bArray = os.toByteArray();

, :
ByteArrayInputStream is = new ByteArrayInputStream(bArray);
ObjectInputStream ois = new ObjectInputStream(is);
Object objRead = ois.readObject();

, :
System.out.println("readed object is: " + objRead.toString());
System.out.println("Object equality is: " + (objSave.equals(objRead)));
System.out.println("Reference equality is: " + (objSave==objRead));

:
readed object is: 1
Object equality is: true
Reference equality is: false

, ( -
), .
,
.
. , ,
,
. :
package demo.io;
import java.io;
class Point implements java.io.Serializable{
double x;
double y;
public Point(double x, double y) {
Java

Rendered by www.RenderX.com

. 17 34

this.x = x;
this.y = y;
}
public String toString() {
return "("+x+","+y+") reference="+super.toString();
}
}
class Line implements java.io.Serializable{
Point point1;
Point point2;
int index;
public Line() {
System.out.println("Constructing empty line");
}
Line(Point p1, Point p2, int index) {
System.out.println("Constructing line: " + index);
this.point1 = p1;
this.point2 = p2;
this.index = index;
}
public int getIndex() {return index;}
public void setIndex(int newIndex) {index = newIndex;}
public void printInfo() {
System.out.println("Line: " + index);
System.out.println(" Object reference: " + super.toString());
System.out.println(" from point "+point1);
System.out.println(" to point "+point2);
}
}
public class Main {
public static void main(java.lang.String[] args) {
Point p1 = new Point(1.0,1.0);
Point p2 = new Point(2.0,2.0);
Point p3 = new Point(3.0,3.0);
Line line1 = new Line(p1,p2,1);
Line line2 = new Line(p2,p3,2);
System.out.println("line 1 = " + line1);
System.out.println("line 2 = " + line2);
String fileName = "d:\\file";
try{
// write objects to file
FileOutputStream os = new FileOutputStream(fileName);
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(line1);
oos.writeObject(line2);
//change state of line 1 and write it again
line1.setIndex(3);
//oos.reset();
oos.writeObject(line1);
Java

Rendered by www.RenderX.com

. 18 34

Serialization

// close stream
// it is enought to close only filter stream
oos.close();
os.close();
//read objects
System.out.println("Read objects:");
FileInputStream is = new FileInputStream(fileName);
ObjectInputStream ois = new ObjectInputStream(is);
while(is.available()>0){
Line line = (Line)ois.readObject();
line.printInfo();
}
}catch(ClassNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
}

, available() ObjectInputStream, InputStream, .


, available() ObjectOutputStream ,
: - (-1),
,
, (,
, ),
, 0.
:
Constructing line: 1
Constructing line: 2
Read objects:
Line: 1
Object reference: study.java.Line@2dc5
from point (1.0,1.0) reference=study.java.Point@322b
to point (2.0,2.0) reference=study.java.Point@3481
Line: 2
Object reference: study.java.Line@5214
from point (2.0,2.0) reference=study.java.Point@3481
to point (3.0,3.0) reference=study.java.Point@5435
Line: 1
Object reference: study.java.Line@2dc5
from point (1.0,1.0) reference=study.java.Point@322b
to point (2.0,2.0) reference=study.java.Point@3481

, Point - point2 point1


- - . ,
Java

Rendered by www.RenderX.com

. 19 34

- , , . ,
, index 3,
1. , , ,
, ,
, ,
. ,
, .
,
.
,
. ,
,
.. ,
, .. -
.
, line1, ,
, . ,
, , ObjectOutputStream
reset().

//reset();

, , line1
. point2
point1 line1. , , - line1
, , Point .
, Line ,
, . ,
-
, Point .
, .
, , -
, .
, , ,
. ,
, ,
,
. . ,
java.io.InvalidClassException .
, ,

class AbstractEntity{
public AbstractEntity(){
System.out.println("Create Abstract Entity");
}
Java

Rendered by www.RenderX.com

. 20 34

Serialization

- , Point, AbstractEntity.
class Point extends AbstractEntity implements java.io.Serializable

, ( ,
Serializable) .
.
.
, , Serializable.
java.io.NotSerializableException .
:
.
, . Point,
, Point.class ,
CLASSPATH. "d:\file",
readObject() ClassNotFoundException.
ObjectInputStream,
java.io.StreamCorruptedException. InputStream
ObjectInputStream ,
,
Java-,
. java.io.StreamCorruptedException
,
InputStream. ObjectInputStream ,
,
java.io.StreamCorruptedException . , InputStream
read() ObjectInputStream, (-1),
. ObjectOutputStream
Java( ObjectOutput DataOutput).
,
Java, java.io.OptionalDataException.
ObjectInputStream,
, ,
, , .
,
,
:
private void writeObject(java.io.ObjectOutputStream out) throws IOException;
private void readObject(java.io.ObjectInputStream in) throws IOException,
ClassNotFoundException;

writeObject , readObject ,
, .
,
Java

Rendered by www.RenderX.com

. 21 34

out.defaultWriteObject();


in.defaultReadObject();


, .
, ,
.
, ,
. ,
, , .
java.io.Externalizable
.

.
, .
, ,
writeExternal() readExternal() Externalizable.
, .
,
Externalizable. Externalizable,
writeExternal . Externalizable, Serializable,
ObjectOutputStream. Externalizable , public ,
readExternal . , Serializable
ObjectInputStream.
writeExternal :
void writeExternal(ObjectOutput out) throws IOException;

, ObjectInput
, .
,
void readExternal(ObjectInput in) throws IOException, ClassNotFoundException;

.

Externalizable readObject, writeObject.
, -
. ,
, .
private, , , ,
Java

Rendered by www.RenderX.com

. 22 34

Serialization

, .
,
-
. -
Externalizable, readObject writeObject -
.
- transient. ,
Account, ,
login name
class Account implements java.io.Serializable {
private String name;
private String login;
private transient String password;
/* Some accessors and mutators for fields
...
*/
}

, ,
null.

2.1.
, ,
. , ,
- , ..
,
.
InvalidClassException. , User,

class User implements java.io.Serializable{
String name;
}

, name :
class User implements java.io.Serializable{
protected String firstName;
protected String lastName;
}

,
InvalidClassException . ,
:
class User implements java.io.Serializable{

Java

Rendered by www.RenderX.com

. 23 34

private String name;


String lastName;
}

, (ID)
. long ( 64 ), . , ,
. ,
, .
, - ,
, ,
, - ,
. , ,
: ,
, ,
.
, :

static transient

, ,

static transient

Serializable Externalizable .

, ,
.
,
. ,
Externalizable, readExternalizable writeExternalizable.

3. Reader Writer. .
- InputStream OutputStream
. , 8-
16-
Unicode - char()
Java. /

Java

Rendered by www.RenderX.com

. 24 34

Reader Writer. .

Reader () Writer ().


.3 .

InputStream OutputStream.
1 .
InputStream

Reader

OutputStream

Writer

ByteArrayInputStream

CharArrayReader

ByteArrayOutputStream

CharArrayWriter

InputStreamReader

OutputStreamWriter

FileInputStream

FileReader

FileOutputStream

FileWriter

FilterInputStream

FilterReader

FilterOutputStream

FilterWriter

BufferedInputStream

BufferedReader

BufferedOutputStream

BufferedWriter

PrintStream

PrintWriter

DataInputStream

DataOutputStream

ObjectInputStream

ObjectOutputStream

PipedInputStream

PipedReader

PipedOutputStream

PipedWriter

Java

Rendered by www.RenderX.com

. 25 34

StringBufferInputStream

StringReader

StringWriter

LineNumberInputStream

LineNumberReader

PushBackInputStream

PushBackReader

SequenceInputStream

, :
, SequenceInputStream
, , ,
Java (DateInput/Output, ObjectInput/Output).
,
, (
). , , : InputStreamReader OutputStreamWriter .
, ,
:

- : FilterReader FilterWriter
, : InputStream OutputStream .

: close Reader flush close Writer ,


InputStream OutputStream

BufferedReader FilterReader, Reader

LineNumberReader FilterReader,
BufferedReader, Reader

FileReader FileWriter - InputStreamReader OutputStreamWriter

available() InputStream, Reader,


ready() - ,
- (
)

,
. , ,
:
String fileName = "d:\\file.txt";
FileWriter fw = null;
BufferedWriter bw = null;
FileReader fr = null;
BufferedReader br = null;
//,
String data = "Some data to be written and readed\n";
Java

Rendered by www.RenderX.com

. 26 34

StreamTokenizer

try{
fw = new FileWriter(fileName);
bw = new BufferedWriter(fw);
System.out.println("Write some data to file: " + fileName);
//
for(int i=(int)(Math.random()*10);--i>=0;)bw.write(data);
bw.close();
fr = new FileReader(fileName);
br = new BufferedReader(fr);
String s = null;
int count = 0;
System.out.println("Read data from file: " + fileName);
// ,
while((s=br.readLine())!=null)
System.out.println("row " + ++count + " read:" + s);
br.close();
}catch(Exception e){
e.printStackTrace();
}

- InputStreamReader OutputStreamWriter
, .
, . ,
, UnsupportedEncodingException.
: "Cp1521", "UTF-8", "8859_1", "8859_2" ...

4. StreamTokenizer
InputStream Reader.
- ,
.
.
StreamTokenizer , ,
.
, ,
nextToken, StreamTokenizer.TT_EOF.
nextToken ttype
. ,
nval. ,
sval.
, -
commentChar, ordinaryChar, parseNumbers, quoteChar, resetSyntax, slashSlashComments,
slashStarComments, whitespaceChars, wordChars.
, , ( )
.

Java

Rendered by www.RenderX.com

File

. 27 34

5. .
5.1. File
, File -
, .
File .
, ,
. ,
exists, true, .
File .
. File
( isDirectory),
list ( String) ( File
- null).
File.
import java.io.*;
public class FileDemo {
public static void findFiles(File file, FileFilter filter, PrintStream output)
throws IOException{
if(file.isDirectory()){
File[] list = file.listFiles();
for(int i=list.length; --i>=0;){
findFiles(list[i], filter, output);
}
}else{
if(filter.accept(file))
output.println("\t" + file.getCanonicalPath());
}
}
public static void main(String[] args) {
class NameFilter implements FileFilter{
private String mask;
NameFilter(String mask){
this.mask = mask;
}
public boolean accept(File file){
return (file.getName().indexOf(mask)!=-1)?true:false;
}
}
File pathFile = new File(".");
String filterString = ".java";
try{
FileFilter filter = new NameFilter(filterString);
findFiles(pathFile, filter, System.out);
}catch(Exception e){
e.printStackTrace();
Java

Rendered by www.RenderX.com

. 28 34

}
System.out.println("work finished");
}
}

(
) , ".java",
-. , ".java"
FileFilter NameFilter.
FileFilter accept, ,
.
- FilenameFilter, accept
: ,
.
, accept.
FileFilter
FilenameFilter. list
File - .
File :

canRead canWrite - boolean ,


exists - boolean ,

getName - - ( )

getParent, getParentName - ,
File

getPath - ( ,
File)

isAbsolutely - boolean , ,
. , - ,
Java-. , Windows -
, '\'. Unix - '/'

isDirectory, isFile - boolean ,


isHidden - boolean ,

lastModified

length

- setReadOnly, setLastModified . -
createNewFile, mkDir, mkDirs. createNewFile
( ), mkDir
, mkDir ,
.

Java

Rendered by www.RenderX.com

RandomAccessFile

. 29 34

- delete deleteOnExit.
delete, , deleteOnExit
Java-( ),
.
File
.

5.2. RandomAccessFile
: DataInput DataOutput , ,
, Java.
, , .
, seek(
getFilePointer) .

: , . ,
String - , File
. (mode) - String,
: "r"() "rw"( ). ,
, mode "r" ( ),
FileNotFoundException. , mode "rw"
, (
FileNotFoundException ).
RandomAccessFile,
DataInput DataOutput .
, , close.

6.
, .

/. ,
java.io ,
( ) .
,
.
InputStream OutputStream,
Reader Writer.
. ,
, , , pipe
(), . ,
BufferedInputStream BufferedOutputStream,
, .
() ( ) Java
DataInputStream, DataOutputStream ( ObjectInputStream, ObjectOutputStream
Java

Rendered by www.RenderX.com

. 30 34

PrintWriter, BufferedReader).
.
() StreamTokenizer.
File
RandomAccessFile.

7.
15-1.
java ?
?
a.)
:

File

byte[] char[]

String

getInputStream() java.net.Socket

Pipe
PipedOutputStream(PipedWriter)

,
(String). , ,
: getOutputStream() Socket.
15-2. File, ,
( )?
? ,
(
)?
a.) equals() File
. ,
File.
( getCanonicalPath() getCanonicalFile())
. , File
, isDirectory(). (
) delete() File.
,
. File
, exist() false
, .
, ,
File, delete() File.

Java

Rendered by www.RenderX.com

. 31 34

15-3. InputStream OutputStream?


/?
a.) ( ) InputStream, OutputStream.
InputStream OutputStream Object.
15-4. write(0x01234567) OutputStream,
?
a.) , write() OutputStream
int,
0x67, 16*6+7=103.
15-5. false?
public static boolean test(InputStream is) throws IOException {
int value = is.read();
return value == (value &amp; 0xff);
}

a.) value == (value & 0xff) true ,


value
( 0xff int 255, 1).
,
,
IOException.
15-6.
Java?
a.) Java,
DataOutput. java.io DataOutputStream. , ObjectOutputStream ObjectOutput,
DataOutput.
15-7. ( ) ( ),
( , )?
?
a.)

:
new PrintWriter(new BufferedWriter(new
FileWriter("file.txt")))

, , , :
new BufferedReader(new FileReader("file.txt"))

BufferedWriter
(
,
Java

Rendered by www.RenderX.com

. 32 34

). ,
FileWriter, - FileReader,
PrintWriter
BufferedReader ( LineNumberReader ).
15-8. PipedWriter
PipedReader? ,
PipedReader?
a.) PipedWriter
PipedReader. PipedReader,
new IOException("Already connected") .
,
PipedReader connect() ,
new IOException("Already connected")
, PipedWriter
PipedReader
PipedWriter.
15-9. Java
write() Writer? print() PrintWriter?
a.) Writer write()
:

write(char cbuf[])

write(char cbuf[], int off, int len)

write(int c)

write(String str)

write(String str, int off, int len)

, int (
byte, char short
int).
print() PrintWriter
Java ( Object String).
15-10. OutputStreamWriter ?
a.) , Java-.
15-11. , print() PrintWriter,
new File(d:\\word.txt) ?
a.) print(Object obj) , ,
String.valueOf(obj).
valueOf(Object obj) String , ,
null,
obj.toString() . , File, ,
getPath(), ,
d:\\word.txt.

Java

Rendered by www.RenderX.com

. 33 34

15-12. RandomAccessFile
(/)?
a.) RandomAccessFile String,
.
r() rw(
). new IllegalArgumentException("mode must be r or rw") ( ,
null, NullPointerException).
15-13. seek() RandomAccessFile,
read()?
a.) , RandomAccessFile,
length(). ,
seek() 0. ,
, seek() randomAccessFile.length()-1 .
15-14. Serializable?
a.) java.io.Serializable .
, ,
.
15-15. , , ObjectOutputStream,
long, int, byte , ,
DataInputStream?
a.) DataInputStream long, int byte,
8 , long, 4 ,
int, , , . ,
, : byte
, int 4
long 8 . ,
, ,
,
, byte, int long ( - )
, .

Java

Rendered by www.RenderX.com

Java ()

Java

Rendered by www.RenderX.com