第 6 章 java 的输入输出与文件处理

76
1 知知知知知知知 知知知知知知知知 知知知知知知 Reader 知 Writer 知知 知知知知知知知知 知知知知知知 知知知知知知 知6知 Java 知知知知知知知知知知

Upload: venice

Post on 26-Jan-2016

88 views

Category:

Documents


8 download

DESCRIPTION

第 6 章 Java 的输入输出与文件处理. 知识点: 流的概念 基本的输入输出流 标准输入输出 Reader 和 Writer 流类 对文件的随机访问 重点: 流的应用 难点: 流的应用. 6.1 Java 的输入输出类库. 包 java.io 6.1.1 流的概念 流 (Stream) :输入流、输出流。. 程序 1. 程序 1. 磁盘文件. 输出流. 输入流. 输入流. 输出流. 输入 / 输出流的概念. 1 数据流: 是指在计算机的输入输出之间运动的数据序列。 - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: 第 6 章  Java 的输入输出与文件处理

1

知识点: 流的概念 基本的输入输出流 标准输入输出 Reader 和 Writer 流类 对文件的随机访问

重点: 流的应用

难点: 流的应用

第 6章 Java 的输入输出与文件处理

Page 2: 第 6 章  Java 的输入输出与文件处理

2

6.1 Java 的输入输出类库 包 java.io

6.1.1 流的概念

流 (Stream) :输入流、输出流。

Page 3: 第 6 章  Java 的输入输出与文件处理

3

输入 / 输出流的概念 1 数据流:

是指在计算机的输入输出之间运动的数据序列。 输入输出是相对程序来说的,程序扮演两个角色:源和目的。

输入流:代表从外设流入程序的数据序列;输出流:代表从程序流向外设的数据序列。

字节流:在输入输出过程中以字节为单位。字符流:在输入输出过程中以字符为单位。

System.out.println : System.out 输出对象 System.in.read() : System.in 输入对象

程序 1 程序 1输入流 输出流 输入流 输出流 磁盘文件

Page 4: 第 6 章  Java 的输入输出与文件处理

4

2 Java 输入 / 输出类层次结构

java.lang.object

java.io.File

java.io.InputStream

java.io.OutputStream

java.io.Write

java.io.Reader

java.io.RandomAccessFile

Page 5: 第 6 章  Java 的输入输出与文件处理

5

InputStream

FileInputStream

ObjectInputStream

FilterInputStream

dataInputStream

BufferedInputStream

Page 6: 第 6 章  Java 的输入输出与文件处理

6

OutpurStream

FileOutputStream

ObjectOutputStream

FilterOutputStream

dataOutputStream

PrintStream

BufferedOutpurStream

Page 7: 第 6 章  Java 的输入输出与文件处理

7

补充: File 类 在 java.io 包中的 File 类提供了平台无关的方式

来描述目录和文件对象的属性。提供了很多的方法用来获取路径、目录和文件的相关信息。

目录管理 文件管理

1. 文件的生成 2. 文件名的处理 3. 文件属性测试 4. 文件信息处理

Page 8: 第 6 章  Java 的输入输出与文件处理

8

一 创建新的文件对象 类 : File 构造函数:

File (“ 目录” ) // 建立文件夹对象File ( “ 目录 \ 文件名” ) // 建立文件对象File (“ 目录”,“文件名” )File ( 文件目录对象,“文件名” )切记:仅建立了一个文件 / 目录的对象,没有做其它事)

例:1 File f1 = new File(“d:\\temp\\test1.dat”);2 File f2 = new File(“d:\\temp”,”test1.dat”);3 File fdir1 = new File(“d:\\temp”); File f3 = new File( fdir1 , “test1”);

Page 9: 第 6 章  Java 的输入输出与文件处理

9

二 File 类提供的方法 一 String getName() 返回表示当前对象的文件名 ( 不带路径 ) 。 String getPath() 返回表示当前对象的路径名。 String getParent() 返回当前 File 对象路径名的父路径名 boolean exists() 当前 File 是否存在。 true/ false

boolean canWrite() 测试是否能写入当前文件 boolean canRead() 测试是否能从指定的文件中进行读取。 boolean isFile() 测试当前 File 对象表示的文件是否是一个文

件。 public boolean isDirectory() 测试 File 对象表示的文件是否是一条路径。

long length() 返回 File 对象指定的字节长度;文件不存在为 0L 。

Page 10: 第 6 章  Java 的输入输出与文件处理

10

File f1 = new File ("d:\\temp\\java1.txt"); //java1.text 建立了吗?

System.out.println( f1.getName() ); System.out.println( f1.getParent() ); System.out.println( f1.toString() ); // 改名 File f2=new File("d:\\temp\\java2.txt"); f1.renameTo( f2);

例题:

Page 11: 第 6 章  Java 的输入输出与文件处理

11

三 建立指定文件 boolean createNewFile() throws IOException

例:try {

File ft=new File ("d:\\temp\\file1.txt");

ft.createNewFile() ;

}catch (IOException ){

System.out.println( e.toString() );}

思考: file1.txt 创建了吗?

Page 12: 第 6 章  Java 的输入输出与文件处理

12

四 文件属性测试 测试文件是否存在

File ft=new File ("d:\\temp\\java2.txt");System.out.println("exists:"+ft.exists() );

五 文件操作 删除文件

public boolean delete()可以删文件或目录

例如:File ft=new File ("d:\\temp\\java2.txt");System.out.println( ft.delete() );

Page 13: 第 6 章  Java 的输入输出与文件处理

13

下列操作:成功 =true 失败 =false 不必异常捕获 boolean mkdir(); // 建目录 boolean mkdirs(); // 同时建立多级目录 boolean renameTo( File dest); // 改目录名 boolean delete( ); // 删除目录

例如:1 ) File fd1 = new File("d:\\temp\\testdir1"); fd1.mkdir() ; // 注意: d:\temp 已经存在 fd1.mkdirs() ;

2 ) fd1.delete(); // 删除 testdir1 目录

六 目录操作:

Page 14: 第 6 章  Java 的输入输出与文件处理

14

File fdir = new File ("e:\\temp"); for (int i=0;i<fdir.list().length;i++){ System.out.println( fdir.list()[i]); }

Page 15: 第 6 章  Java 的输入输出与文件处理

15

File f1 ; String filename,filePath; File fdir = new File ("e:\\temp"); for (int i=0;i<fdir.list().length;i++){ filename = fdir.list()[i] ; filePath = fdir.getPath()+"\\"+filename; f1 = new File ( filePath ); System.out.print( f1.getName()+"," ); if( f1.isFile() ) { System.out.print( " 文件 " ); System.out.print( ", 路径 :"+f1.getPath() ); System.out.print( ", 大小 :"+f1.length() ); } else System.out.print( " 文件夹 " ); System.out.println(); }

Page 16: 第 6 章  Java 的输入输出与文件处理

16

练习 一 写出结果

File f1 = new File ("d:\\temp\\java1.txt"); System.out.println( f1.getName() ); System.out.println( f1.getParent() ); System.out.println( f1.toString() );

二 完成下列操作 1 )用程序创建一个文件夹: d:\data1 2) 在 d:\data1 下建立空文件 test1.txt 3) 测试 d:\data1\test1.txt 是否存在 4) 用文本编辑器打开 test1.txt , 输入 abcd, 然后存储。 测试 test1.txt 的文件长度。 5 )把 test1.txt 重命名为 mytest.txt 5 )删除 d:\data1\mytest.txt 文件 6) 删除 目录 d:\data1

Page 17: 第 6 章  Java 的输入输出与文件处理

17

6.1.2 输入输出流类库

Java 的流类都封装在 java.io 包中,在该类库中的每一个类都代表了一种特定的输入或输出流。 InputStream 、 OutputStream :“位流” (b

it stream) ,也就是二进制文件,但也可以处理纯文本文件;

Reader 、 Writer 类则是用来处理“字符流” (character stream) ,也就是纯文本文件 (text file) 。

Page 18: 第 6 章  Java 的输入输出与文件处理

18

InputStream

FileInputStream

ObjectInputStream

FilterInputStream

dataInputStreamOutpurStream

FileOutputStream

ObjectOutputStream

FilterOutputStream

dataOutputStream

Page 19: 第 6 章  Java 的输入输出与文件处理

19

6.2 使用 InputStream 和 OutputStream流类

InputStream 和 OutputStream 类是 Java里用来处理以位 (bit) 为主的流,也就是说,除了纯文本文件之外,它们也可用来处理二进制文件(binary file) 的数据。

10.2.1 基本的输入输出流一 字节输入流 InputStream (抽象类 )

Page 20: 第 6 章  Java 的输入输出与文件处理

20

表 10.1 InputStream 类的常用方法 方 法 功 能 说 明

public int read()

从输入流中的当前位置读入一个字节 (8bit)的二进制数据,然后以此数据为低位字节,配上 8个全 0的高位字节合成一个 16位的整型量 (0~ 255)返回给调用此方法的语句,若输入流中的当前位置没有数据,则返回 -1。

public int read(byte b[])

从输入流中的当前位置连续读入多个字节保存在数组b[]中,同时返回所读到的字节数。

public int read(byte b[],

int off,int len)

从输入流中的当前位置连续读入 len个字节,从数组 b[]的第 off+1个元素位置处开始存放,同时返回所读到的字节数。

public int available() 返回输入流中可以读取的字节数。public long skip(long

n)使位置指针从当前位置向后跳过 n个字节。

public void mark() 在当前位置处做一个记号。public void reset() 将位置指针返回到标记的位置。public void close() 关闭输入流与外设的连接并释放所占用的系统资源。

Page 21: 第 6 章  Java 的输入输出与文件处理

21

InputStream 方法:下列方法抛出 IOException int read() // 返回 -1 表示输入结束 int read( byte[ ] b ) // 读入字节到数组 b ,长度

为 b 的长度 int available() //还有多少字节可读 long skip( long n) //跳过几个字节

Page 22: 第 6 章  Java 的输入输出与文件处理

22

文件输入流 FileInputStream 完成对本地磁盘文件的顺序输入输出操作。

FileInputStream 继承 InputStream

覆盖、实现: read , skip , close等方法。 构造函数: 下列两方法抛出 FileNotFoundEx

ception ;FileInputStream(String filename) FileInputStream( File file);

关闭 FileInputStream 流void close() throws IOException

Page 23: 第 6 章  Java 的输入输出与文件处理

23

建立文件对象: 例 1 :

try {

FileInputStream f1 =

new FileInputStream( “d:\\data\\test.txt”)

} catch( FileNotFoundException e) { }

例 2 : try {

File myFile = new File( “d:\\data\\test1.txt”);

FileInputStream f2 = new FileInputStream( myFile );

} catch( FileNotFoundException e) { }

Page 24: 第 6 章  Java 的输入输出与文件处理

24

例题:从一个文件读入数据,并显示

读入一个文件: 1 ) 建立文件对象 2 ) 读入 3 )关闭

Page 25: 第 6 章  Java 的输入输出与文件处理

25

FileInputStream f1 ;try{ f1 = new FileInputStream("d:\\temp\\test.txt"); int nData ; do { nData = f1.read() ; //一次读入一个字节 if (nData != -1 ) //文件没有结束 System.out.print( (char) nData ); } while ( nData != -1 ) ;

f1.close(); } catch(FileNotFoundException e){ System.out.println( e); } catch( IOException e ) { System.out.println( "read file error!"); }

Page 26: 第 6 章  Java 的输入输出与文件处理

26

例题:以更高的效率读入数据流

FileInputStream f1 ;try{ f1 = new FileInputStream("d:\\temp\\tes.txt"); byte bData[ ] = new byte[20] ; while (true) { if ( f1.read( bData ) == -1 ) break; System.out.print( new String( bData ) ); } f1.close(); } catch( IOException e ) { System.out.println( "read file error!"); }

Page 27: 第 6 章  Java 的输入输出与文件处理

27

二 OutputStream 流类

OutputStream 类中包含一套所有输出都需要的方法,可以完成最基本的向输出流写入数据的功能,其中常用的方法及功能见表 10.2 。

Page 28: 第 6 章  Java 的输入输出与文件处理

28

表 10.2 OutputStream 类的常用方法 方 法 功 能 说 明

public void write(int b) 将参数 b的低位字节写入到输出流。

public void write(byte b[])

将字节数组 b[]中的全部字节按顺序写入到输出流。

public void write(byte b[],int off,int len)

将字节数组 b[]中第 off+1个元素开始的 len个数据,顺序地写入到输出流。

public void flush() 强制清空缓冲区并执行向外设写操作。

public void close() 关闭输出流与外设的连接并释放所占用的系统资源。

Page 29: 第 6 章  Java 的输入输出与文件处理

29

字节输出流 OutputStream

下列方法抛出 IOException void write( int b) void write(byte b[ ]) // 输出字节数组 void write(byte b[ ] , int off , int len) void fulsh() //刷新

Page 30: 第 6 章  Java 的输入输出与文件处理

30

文件输出流 FileOutputStream: 完成对本地磁盘文件的顺序输出操作。

FileOutputStream 继承 outputStream

构造函数: 抛出 IOException FileOutputStream( File file ); FileOutputStream(String filename ); FileOutputStream( File file,boolean append);

append: true 存在则追加 / false :存在覆盖原文件

关闭 FileOutputStreamvoid close()

Page 31: 第 6 章  Java 的输入输出与文件处理

31

//输出流:生成文件byte buf1[ ] = { ‘a’,’p’,’p’,’l’,’e’};byte buf2[ ] = { ‘c’,’a’,’r’}; try { FileOutputStream fo = new FileOutputStream ("d:\\temp\\test2.txt"); for (int i=0;i<buf1.length;i++) fo.write( buf1[i] ) ;

for (int i=0;i<buf2.length;i++) fo.write( buf2[i] ) ;

fo.flush(); fo.close(); } catch( IOException e){

System.out.println(e.toString() );}

fo.write( 13) ;fo.write(10); //换行

Page 32: 第 6 章  Java 的输入输出与文件处理

32

//输出流:生成文件byte buf1[ ] = { ‘a’,’p’,’p’,’l’,’e’};byte buf2[ ] = { ‘c’,’a’,’r’}; try { FileOutputStream fo = new FileOutputStream ("d:\\temp\\test2.txt");

fo.write( buf1 ) ; fo.write( buf2 ) ;

fo.flush(); fo.close(); } catch( IOException e){

System.out.println(e.toString() );}

Page 33: 第 6 章  Java 的输入输出与文件处理

33

练习:1 把 abcdefghijk 123456789 写入文件: d:\data\test1.txt2 把文件 test1.txt 读出并显示。3 把 n 行的下列图案输出到文件 star.txt 中。 * * * * * * * * * * * * * 4 1) 把乘法口诀写入文件 multi.txt 2) 读出 multi.txt 文件的内容

Page 34: 第 6 章  Java 的输入输出与文件处理

34

int d;try{ FileInputStream fin= new FileInputStream("e:\\temp\\t1.dat"); do{ d = fin.read(); if (d!=-1) System.out.print( (char)d ); } while(d!=-1); } catch(IOException e){ System.out.println(e);}

try{ FileOutputStream fo = new FileOutputStream ("e:\\temp\\t1.dat");

fo.write('a');fo.write('b');fo.write('c');fo.write(65); fo.write(13);fo.write(10); fo.write('1');fo.write('2');fo.write('3'); }catch(IOException e){ System.out.println("error");}

Page 35: 第 6 章  Java 的输入输出与文件处理

35

byte bb[]=new byte[3] ; try{ FileInputStream fin= new FileInputStream("e:\\temp\\t1.dat"); do{ d = fin.read(bb); if (d!=-1) System.out.print( new String(bb) ); } while(d!=-1); }catch(IOException e){System.out.println(e);}

Page 36: 第 6 章  Java 的输入输出与文件处理

36

4 基本数据类型的输入 / 输出流 DataInputStream , DataOutputStream 注意:与 FileInputStream 的区别

1) DataInputStream : 继承 FilterInputStream 构造函数: 抛出 FileNotFoundException

DataInputStream( InputStream in ) ; 方法:抛出 IOException , 读到文件尾 EOFException

byte readByte(); // 读一个字节void read( byte b[ ]); boolean readBoolean()short readShort(); (2 字节 )int readInt() ; (4 字节 )int readFloat() ; int readDouble() ;String readUTF() ; // 字符串

Page 37: 第 6 章  Java 的输入输出与文件处理

37

文件对象:

FileInputStream fin = new FileInputStream( “d:\\dat1.dat”)

DataInputStream ds = new DataInputStream( fin) ;

Page 38: 第 6 章  Java 的输入输出与文件处理

38

// 示例:读入文件 try{ FileInputStream fin= new FileInputStream("d:\\dat1.dat"); DataInputStream ds = new DataInputStream( fin) ; int no , age; String name; no = ds.readInt( ); //整型数 name = ds.readUTF(); // 字符串 age = ds.readInt( ); //整型数 System.out.println( “data:"+no+"/"+name +"/"+age) ; ds.close(); // 关闭 DataInputStream fin.close(); // 关闭 FileInputStream } catch(IOException e){ System.out.println( "read file error!"); }

Page 39: 第 6 章  Java 的输入输出与文件处理

39

2) DataOutputStream 构造函数:

DataOutputStream( outputStream out) ;

方法:void writeByte( int data); //8void write( byte b[ ]);void writeBoolean( boolean data)void writeInt( int data) ; (32)void writeDouble( double data) ; void writeUTF(String data) ; // 字符串int size() ; //共写了多少个字节数

Page 40: 第 6 章  Java 的输入输出与文件处理

40

文件对象: FileOutputStream fo=new FileOutputStream( “d:\\dat1.dat”)

DataOutputStream dos = new DataOutputStream( fo) ;

Page 41: 第 6 章  Java 的输入输出与文件处理

41

// 示例:生成文件 try{ FileOutputStream fo=new FileOutputStream("d:\\dat1.dat"); DataOutputStream ds = new DataOutputStream( fo) ; int no , age; String name; no=1001; age = 22; name=“zhang”; ds.writeInt( no ); //整型数 ds.writeUTF( name); // 字符串 ds.writeInt(age ); //整型数 ds.close(); // 关闭 DataOutputStream fo.close(); // 关闭 FileOutputStream } catch(IOException e){ System.out.println( "read file error!"); }

Page 42: 第 6 章  Java 的输入输出与文件处理

42

练习: 有 2 个学生 学号 姓名 语文 数学 1001 张三 97 88

1003 赵英 85 71

1 编写程序将 2学生的数据写入文件 grade.dat

2) 编写程序从 grade.dat 中读出数据,计算每个学生的平均分,然后每个学生一行,平均分显示在最后一列。

Page 43: 第 6 章  Java 的输入输出与文件处理

43

try{ // 1 )生成存储 2 个学生成绩的文件 FileOutputStream fo= new FileOutputStream("d:\\dat1.dat"); DataOutputStream dso = new DataOutputStream( fo) ; String sNo,sName ; int grade1,grade2 ; //

sNo=“1001” ;sName =“张三” ;grade1=97;grade2=88dso.writeInt( sNo ); dso.writeUTF( sName); // 字符串dso.writeInt( grade1); dso.writeInt( grade2);

sNo=“1003” ;sName =“赵英” ;grade1=85;grade2=71; dso.writeInt( sNo ); dso.writeUTF( sName); // 字符串dso.writeInt( grade1); dso.writeInt( grade2);

dso.flush(); dso.close(); // 关闭 DataOutputStream fo.close(); // 关闭 FileOutputStream} catch(IOException e){ System.out.println( “write file error!"); }

Page 44: 第 6 章  Java 的输入输出与文件处理

44

//2 读入学生数据并计算平均分try{ FileOutputStream fo= new FileOutputStream("d:\\dat1.dat"); DataOutputStream ds = new DataOutputStream( fo) ; String sNo,sName ; int grade1,grade2 ,avgGrade ;

sNo = ds.readUTF( ); sName = ds.readUTF(); grade1 = ds.readInt( ); grade2=ds.readInt(); avgGrade = (grade1+grade2) /2 ; System.out.println( sNo+“ "+sName +“ "+grade1+” “+grade

2 + “ “+avgGrade) ;

ds.close(); // 关闭 DataInputStream fo.close(); // 关闭 FileInputStream } catch(IOException e){ System.out.println( "read file error!"); }

Page 45: 第 6 章  Java 的输入输出与文件处理

45

练习 2 :改错

DataOutputStream dso = new DataOutputStream(“d:\\test2.dat” ) ;String name ;int no;name=“zhang”;no=1001;dso.write( no );dso.write(name);dso.close();

Page 46: 第 6 章  Java 的输入输出与文件处理

46

二进制图形文件 .gif 的拷贝。

import java.io.*;public class app10_2 { ////app10_2.java 读写二进制文件public static void main(String args[]) throws IOException{ FileInputStream fi= new FileInputStream("d:\\gificon.gif"); FileOutputStream fo= new FileOutputStream("d:\\newicon.gif"); System.out.println(" 文件的大小 ="+fi.available()); byte b[]=new byte[ fi.available() ]; fi.read( b ); fo.write(b); System.out.println(" 文件已被拷贝并被更名 "); fi.close(); fo.close(); } }

Page 47: 第 6 章  Java 的输入输出与文件处理

47

练习: 编写一个文件复制程序,完成一个文件复制成另一个文件名。

如: java filecopy abc.exe aaa.exe

生成源文件对象 准备读

生成目的文件对象 准备写

从源文件读一个字节

源文件结束吗?

把字节写入目的文件

关闭源文件、目的文件

No

Yes

Page 48: 第 6 章  Java 的输入输出与文件处理

48

import java.io.*;class filecopy { //方案一static void copy( String source,String dest){ try{ FileInputStream fin=new FileInputStream( source); FileOutputStream fo=new FileOutputStream( dest); int b1=0; while ( true ){ b1= fin.read() ; //read if (b1==-1) break; fo.write( b1 ); //write } fin.close(); fo.close(); } catch(IOException e){ System.out.println( e.toString()); }} public static void main(String args[]){ copy(args[0],args[1]); }

Page 49: 第 6 章  Java 的输入输出与文件处理

49

import java.io.*;class filecopy { static void copy( String source,String dest){ try{ FileInputStream fin= new FileInputStream( source); DataInputStream din = new DataInputStream( fin) ; FileOutputStream fo= new FileOutputStream( dest); DataOutputStream dso=new DataOutputStream( fo) ; int b1=0; while ( true ){ try { b1=(int) din.readByte() ; //read dso.writeByte( b1 ); //write } catch (EOFException e){ break;} } System.out.println( "copy size="+dso.size() ) ; din.close(); fin.close(); dso.close(); fo.close(); } catch(IOException e){ System.out.println( e.toString()); } }

public static void main(String args[]){ copy(args[0],args[1]); }

public static void main(String args[]){ copy(args[0],args[1]); }

Page 50: 第 6 章  Java 的输入输出与文件处理

50

如果一次读入 2k ,如何编写 FileCopy

Page 51: 第 6 章  Java 的输入输出与文件处理

51

import java.io.*; //2K字节class filecopy { static void copy( String source,String dest){ byte [] buf = new byte[2048]; try{ FileInputStream fin=new FileInputStream( source); FileOutputStream fo=new FileOutputStream( dest); do{ if (fin.read(buf)!=-1) fout.write(buf); else break; }while( true) ; fin.close(); fout.close(); }catch(Exception ee) { System.out.println(ee.getMessage()) ; } } public static void main(String args[]){ copy(args[0],args[1]); }

Page 52: 第 6 章  Java 的输入输出与文件处理

52

InputStream

FileInputStream

ObjectInputStream

FilterInputStream

dataInputStream

BufferedInputStream

Page 53: 第 6 章  Java 的输入输出与文件处理

53

OutpurStream

FileOutputStream

ObjectOutputStream

FilterOutputStream

dataOutputStream

PrintStream

BufferedOutpurStream

Page 54: 第 6 章  Java 的输入输出与文件处理

54

5 带缓存输入 / 输出

BufferedInputStream 继承 FilterInputStream BufferedOutputStream 继承 FilterOutputStream

BufferedInputStream 构造方法: BufferedInputStream ( InputStream in) BufferedInputStream ( InputStream in , int size)

BufferedOutputStream 构造方法: BufferedOutputStream ( OutputStream in) BufferedOutputStream ( OutputStream in , int size)

size : 缓冲区大小 ,单位 byte

Page 55: 第 6 章  Java 的输入输出与文件处理

55

// 示例:带缓存生成文件try{ FileOutputStream fo= new FileOutputStream("d:\\dat1.dat"); BufferedOutputStream bo = new BufferedOutputStream( fo ); for (long i=1;i<20000000;i++ ) bo.write( 65 ); bo.close(); fo.close(); } catch(IOException e){

System.out.println( "read file error!"); }

Page 56: 第 6 章  Java 的输入输出与文件处理

56

import java.io.*;import java.util.*;import java.text.*;public class fileTest { //计算时间public static void main(String[] args) { Date currentTime = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println( formatter.format(currentTime) ); try{ FileOutputStream fo= new FileOutputStream("e:\\dat1.dat");

for (long i=1;i<20000000;i++ ) fo.write( 65 ); fo.close();

} catch(IOException e){ System.out.println( "read file error!"); } currentTime = new Date(); System.out.println( formatter.format(currentTime) ); } }

Page 57: 第 6 章  Java 的输入输出与文件处理

57

try{ // 带缓存读入 FileInputStream fin= new FileInputStream("d:\\temp\\dat1.dat"); BufferedInputStream bin = new BufferedInputStream( fin ); int d=0; for (long i=1;i<2000000;i++ ) { d = bin.read();

if (i/100 ==0) System.out.print( ( char) d );

}

bin.close(); fin.close(); } catch(IOException e){ System.out.println( "read file error!"); }

Page 58: 第 6 章  Java 的输入输出与文件处理

58

练习: 编写一个文件复制程序,完成一个文件复制成另一个文件名。用一个 2k 的缓存支持拷贝。

如: java filecopy abc.exe aaa.exe

Page 59: 第 6 章  Java 的输入输出与文件处理

59

boolean copy( String source , String dest) { FileInputStream fin=new FileInputStream ( source ); FileOutputStream fout=new FileOutputStream ( dest ); BufferedInputStream bin = new BufferedInputStream( fin , 2048); BufferedOutputStream bo = new BufferedOutputStream( fout , 2048) ; byte data [ ] = new byte [512]; long nCnt =0; while (true) { nCnt = bin.available(); if ( bin.read( data ) == -1 ) break; else bo.write( data); } bin.close();bo.close();}

Page 60: 第 6 章  Java 的输入输出与文件处理

60

6.标准输入输出

System.in BufferInputStream 的对象 System.out PrintStream 的对象

try { int c1; c1 = System.in.read(); System.out.print( c1) ;} catch(IOException e) { }

Page 61: 第 6 章  Java 的输入输出与文件处理

61

字符流

10.3 使用 Reader 和 Writer 流类

Page 62: 第 6 章  Java 的输入输出与文件处理

62

一 Reader/Writer ( abstract) 1 Reader 方法:

int read() throws IOExceptionint read( char[ ] b) throws IOException

返回 – 1 表示到文件尾

2 Writer 下列方法 throws IOExceptionvoid write( int c) 写一字符,忽略高 16 位 void write( char[ ] b) 写一个字符数组void write(String s) 写一个字符串。 void flush()

Page 63: 第 6 章  Java 的输入输出与文件处理

63

java.io.Reader

java.io.FileReader

java.io.Writer

java.io.OutputStreamWriter

java.io.BufferedReader

java.io.FileWriter

java.io. InputStreamReader

java.io. BufferedWriter

Page 64: 第 6 章  Java 的输入输出与文件处理

64

二、 FileReader/FileWrite

1 FileReader 构造方法: 抛出 FileNotFoundException

FileReader(String fileName) FileReader(File file)

2 FileWrite 构造方法:抛出 IOException FileWrite( String fileName) FileWrite( File f) FileWrite(String fileName, boolean append)

Page 65: 第 6 章  Java 的输入输出与文件处理

65

生成一个文本文件 file1.txt , 存储内容为: abcde

abcdefgh

1234567890

try{

FileWriter f = new FileWriter( "d:\\file1.txt",true);

f.write( "abcde" ); f.write('\r');f.write('\n');

f.write( "abcdefgh" ); f.write('\r');f.write('\n');

f.write( "1234567890" ); f.write('\n');

f.close();

} catch( IOException e){ }

Page 66: 第 6 章  Java 的输入输出与文件处理

66

try{ // 读文本文件 FileReader f = new FileReader( "d:\\file1.txt"); int data;

while (true) { data=f.read(); if (data==-1) break; System.out.print( (char)data ); } f.close(); } catch (FileNotFoundException e){ } catch( IOException e){ }

Page 67: 第 6 章  Java 的输入输出与文件处理

67

作业: 1 用记事本生成一个文件 hi.txt ,输入一些内容(英

文字母、数字)。编写一个程序,读出此文件, 1 )统计输出此文件有多少行。 2 )统计文章出现了多少次 apple 这个单词。

2 编写程序 , 从键盘输入: abcdefghijklmnopqrstuvwxyz 12345678901234567890 Hello,how do you do!

1) 把输入的内容写入文件: test.txt 2) 从文件 test.txt 读出内容,并显示在屏幕上。

Page 68: 第 6 章  Java 的输入输出与文件处理

68

10.3.3 BufferedReader/BufferedWriter

一 BufferedReader 1 构造方法:

BufferedReader( Reader in) 或 inputStreamReader BufferedReader( Reader in , int size)

2 方法 int read() -1 文件结束 int read(char [] ) -1 文件结束 String readLine() null 文件结束

Page 69: 第 6 章  Java 的输入输出与文件处理

69

二 BufferedWriter 1 构造方法:

BufferedWriter( Writer out) //OutputStreamReader BufferedWriter( Writer out , int size)

2 方法 void write( int c) 抛出 IOException void write(char [ ] ) void write(String s) void newLine() //换行

Page 70: 第 6 章  Java 的输入输出与文件处理

70

try {FileWriter fw1 = new FileWriter("d:\\test1.txt");BufferedWriter bw = new BufferedWriter(fw1);bw.write("上海师范大学 ");bw.newLine();

bw.write("better city,better life"); bw.close(); fw1.close(); } catch(IOException e ){ }

Page 71: 第 6 章  Java 的输入输出与文件处理

71

try {FileReader r1 = new FileReader("d:\\test1.txt");BufferedReader rw = new BufferedReader(r1);String s1;while (true){ s1 = rw.readLine(); if (s1==null) break;

System.out.println(s1 );}rw.close();

r1.close(); } catch(IOException e ){ }

Page 72: 第 6 章  Java 的输入输出与文件处理

72

三 InputStreamReader 一个 InputStreamReader 类是从字节流到字符流的桥梁:它读入字节,将之转换为字符流 。

四 OutputStreamReader 将字符写入到一个输出流,字符转换为字节

Page 73: 第 6 章  Java 的输入输出与文件处理

73

从标准设备读入数据:

String s1;

InputStreamReader sr =

new InputStreamReader( System.in) ;

BufferedReader br = new BufferedReader (sr);s1 = br.readLine();

Page 74: 第 6 章  Java 的输入输出与文件处理

74

练习:1 )把乘法口诀表输出到文件 formula.txt 文件 [BufferedReade

r]1*1=12*1=2 2*2=43*1=3 3*2=6 3*3=94*1=4 4*2=8 4*3=12 4*4=165*1=5 5*2=10 5*3=15 5*4=20 5*5=256*1=6 6*2=12 6*3=18 6*4=24 6*5=30 6*6=367*1=7 7*2=14 7*3=21 7*4=28 7*5=35 7*6=42 7*7=498*1=8 8*2=16 8*3=24 8*4=32 8*5=40 8*6=48 8*7=56 8*8=649*1=9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=

812) 读出 formula.txt 文件,显示在屏幕上。

Page 75: 第 6 章  Java 的输入输出与文件处理

75

try{ RandomAccessFile f1= newRandomAccessFile("d:\\student.dat" , "rw"); f1.writeUTF("A001");f1.writeUTF("张三 "); f1.writeInt(89);f1.writeFl

oat( 80.4f );

f1.writeUTF("A002");f1.writeUTF("张四 "); f1.writeInt(91);f1.writeFloat( 81.4f );

f1.writeUTF("A003");f1.writeUTF("钱银 "); f1.writeInt(92);f1.writeFloat( 82.4f );

f1.writeUTF("A004");f1.writeUTF("李俊 "); f1.writeInt(93);f1.writeFloat( 83.4f ); // 4+2 7+2 4 4 = 23

// 修改 A003 的 92-- 〉 99//f1.seek(0);f1.seek(23+23+15); f1.writeInt(99);

Page 76: 第 6 章  Java 的输入输出与文件处理

76

// 显示 int dData; f1.seek(0); while (true){

System.out.print( f1.readUTF()+" " ); System.out.print( f1.readUTF()+" " ); System.out.print( dData = f1.readInt() ); System.out.print( " "+f1.readFloat() ); System.out.println(); if (dData == -1 ) break; }

f1.close();}catch(IOException e){

System.out.println(e.getMessage());}