1 / 76

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

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

venice
Download Presentation

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

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 第6章 Java的输入输出与文件处理 知识点: 流的概念 基本的输入输出流 标准输入输出 Reader和Writer流类 对文件的随机访问 重点: 流的应用 难点: 流的应用

  2. 6.1 Java的输入输出类库 包 java.io 6.1.1 流的概念 流(Stream):输入流、输出流。

  3. 程序1 程序1 磁盘文件 输出流 输入流 输入流 输出流 输入/输出流的概念 • 1 数据流: • 是指在计算机的输入输出之间运动的数据序列。 • 输入输出是相对程序来说的,程序扮演两个角色:源和目的。 输入流:代表从外设流入程序的数据序列; 输出流:代表从程序流向外设的数据序列。 字节流:在输入输出过程中以字节为单位。 字符流:在输入输出过程中以字符为单位。 System.out.println : System.out 输出对象 System.in.read() :System.in 输入对象

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

  5. InputStream FileInputStream ObjectInputStream FilterInputStream dataInputStream BufferedInputStream

  6. 补充:File 类 • 在java.io包中的File类提供了平台无关的方式来描述目录和文件对象的属性。提供了很多的方法用来获取路径、目录和文件的相关信息。 • 目录管理 • 文件管理 • 1.文件的生成 • 2.文件名的处理 • 3.文件属性测试 • 4.文件信息处理

  7. 一 创建新的文件对象 • 类: 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”);

  8. 二 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。

  9. 例题: • 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);

  10. 三 建立指定文件 boolean createNewFile() throws IOException 例: try { File ft=new File ("d:\\temp\\file1.txt"); ft.createNewFile() ; }catch (IOException ){ System.out.println( e.toString() );} 思考: file1.txt 创建了吗?

  11. 四 文件属性测试 • 测试文件是否存在 • 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() );

  12. 六 目录操作: • 下列操作:成功=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目录

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

  14. 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(); }

  15. 练习 • 一 写出结果 • 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

  16. 6.1.2 输入输出流类库 Java的流类都封装在java.io包中,在该类库中的每一个类都代表了一种特定的输入或输出流。 InputStream、OutputStream:“位流”(bit stream),也就是二进制文件,但也可以处理纯文本文件; Reader、Writer类则是用来处理“字符流”(character stream),也就是纯文本文件(text file)。

  17. 6.2 使用InputStream和OutputStream流类 InputStream和OutputStream类是Java里用来处理以位(bit)为主的流,也就是说,除了纯文本文件之外,它们也可用来处理二进制文件(binary file)的数据。 10.2.1 基本的输入输出流 一 字节输入流 InputStream (抽象类)

  18. 表10.1 InputStream类的常用方法

  19. InputStream 方法:下列方法抛出 IOException • int read() //返回 -1 表示输入结束 • int read( byte[ ] b ) //读入字节到数组 b,长度为b的长度 • int available() //还有多少字节可读 • long skip( long n) //跳过几个字节

  20. 文件输入流 FileInputStream 完成对本地磁盘文件的顺序输入输出操作。 • FileInputStream 继承 InputStream • 覆盖、实现:read ,skip , close等方法。 • 构造函数: 下列两方法抛出 FileNotFoundException ; • FileInputStream(String filename) • FileInputStream( File file); • 关闭 FileInputStream 流 • void close() throws IOException

  21. 建立文件对象: • 例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) { }

  22. 例题:从一个文件读入数据,并显示 • 读入一个文件: • 1) 建立文件对象 • 2) 读入 • 3)关闭

  23. 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!"); }

  24. 例题:以更高的效率读入数据流 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!"); }

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

  26. 表10.2 OutputStream类的常用方法

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

  28. 文件输出流 FileOutputStream: 完成对本地磁盘文件的顺序输出操作。 FileOutputStream 继承 outputStream 构造函数: 抛出 IOException • FileOutputStream( File file ); • FileOutputStream(String filename ); • FileOutputStream( File file,boolean append); • append: true 存在则追加 / false:存在覆盖原文件 • 关闭 FileOutputStream • void close()

  29. //输出流:生成文件 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); //换行

  30. //输出流:生成文件 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() ); }

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

  32. 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");} 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);}

  33. 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);}

  34. 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() ; //字符串

  35. 文件对象: FileInputStream fin = new FileInputStream( “d:\\dat1.dat”) DataInputStream ds = new DataInputStream( fin) ;

  36. //示例:读入文件 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!"); }

  37. 2) DataOutputStream • 构造函数: • DataOutputStream( outputStream out) ; • 方法: • void writeByte( int data); //8 • void write( byte b[ ]); • void writeBoolean( boolean data) • void writeInt( int data) ; (32) • void writeDouble( double data) ; • void writeUTF(String data) ; //字符串 • int size() ; //共写了多少个字节数

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

  39. //示例:生成文件 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!"); }

  40. 练习: 有2个学生 学号 姓名 语文 数学 1001 张三 97 88 1003 赵英 85 71 1 编写程序将2学生的数据写入文件 grade.dat 2) 编写程序从 grade.dat 中读出数据,计算每个学生的平均分,然后每个学生一行,平均分显示在最后一列。

  41. 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=88 dso.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!"); }

  42. //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+” “+grade2 + “ “+avgGrade) ; ds.close(); //关闭 DataInputStream fo.close(); //关闭 FileInputStream } catch(IOException e){ System.out.println( "read file error!"); }

  43. 练习2:改错 DataOutputStream dso = new DataOutputStream(“d:\\test2.dat” ) ; String name ; int no; name=“zhang”; no=1001; dso.write( no ); dso.write(name); dso.close();

  44. 二进制图形文件.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(); } }

  45. 生成源文件对象 准备读 • 练习: 编写一个文件复制程序,完成一个文件复制成另一个文件名。 • 如: java filecopy abc.exe aaa.exe 生成目的文件对象 准备写 从源文件读一个字节 Yes 源文件结束吗? No 把字节写入目的文件 关闭源文件、目的文件

  46. 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]); }

  47. 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]); • }

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

More Related