首页 java流式输入输出与文件处理编程

java流式输入输出与文件处理编程

举报
开通vip

java流式输入输出与文件处理编程实验10  流式输入输出与文件处理 10.1 实验目的 (1) 掌握字节流和字符流的特点和处理差异; (2) 掌握过滤流的使用; (3) 掌握File类的使用; (4) 掌握随机文件的使用。 (5) 掌握对象系列化的概念以及访问文件时对象读写方法。 10.2 知识要点 10.2.1  面向字节的输入/输出流 (1)类InputStream是面向字节的输入流的根。其主要方法见表13-1。 表13-1 类InputStream的方法 方法 功能 int read() 读一个字节 int read(...

java流式输入输出与文件处理编程
实验10  流式输入输出与文件处理 10.1 实验目的 (1) 掌握字节流和字符流的特点和处理差异; (2) 掌握过滤流的使用; (3) 掌握File类的使用; (4) 掌握随机文件的使用。 (5) 掌握对象系列化的概念以及访问文件时对象读写方法。 10.2 知识要点 10.2.1  面向字节的输入/输出流 (1)类InputStream是面向字节的输入流的根。其主要方法见 关于同志近三年现实表现材料材料类招标技术评分表图表与交易pdf视力表打印pdf用图表说话 pdf 13-1。 表13-1 类InputStream的方法 方法 功能 int read() 读一个字节 int read(byte b[]) 读多个字节到字节数组 int read(byte[] b, int off, int len) 读指定长度的数据到字节数组,数据从字节数组的off处开始存放 Long skip(long n) 输入指针跳过n个字节 Void mark() 在当前指针位置处做一标记 Void reset() 将位置指针返回标记处 Void close() 关闭流 (2)       数据过滤流DataInputStream 该流实现DataInput接口,主要方法有:readByte(),readBoolean()、readShort()、readChar()、readInt() 、readLong()、readFloat()、readDouble()、readUTF()等。 (3)类OutputStream是面向字节输出流的根,其主要方法有:          void write(int b) :将参数b的低字节写入输出流          void write(byte b[]) :将字节数组全部写入输出流          void write(byte b[],int offset, int len):将字节数组中从b[offset]开始处的len个字节写入至输出流。 (4)类DataOutputStream实现各种类型数据的输出处理,它实现了DataOutput接口,主要方法有:writeByte(int)、writeBytes(String)、writeBoolean(boolean)、writeChars(String)、writeInt(int) 、writeLong()、writeFloat(float)、writeDouble(double)、writeUTF(String)等。 10.2.2 面向字符的输入与输出流 类Reader是面向字符的输入流的根,其提供的方法与InputStream类似,只是将基于Byte的参数改为基于Char。 类Writer是面向字符的输出流类的根,其提供的方法与OutputStream类似,只是将基于Byte的参数改为基于Char。 类InputStreamReader是一个特殊的流,用来将面向字节的数据流包装转换为面向字符的流。常用于从键盘获取输入数据。例如,从键盘输入一行字符串,可以用BufferedReader的readLine()方法,但在此前必须使用InputStreamReader将字节流转化为字符流。  BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); String x=in.readLine()   10.2.3  文件的顺序读写 (1)面向字节的文件访问          以二进制文件作为数据源。FileInputStream类和FileOutputStream类分别用于文件的读、写访问。          利用InputStream和OutputStream的方法可实现文件的读写操作。          可用DataInputStream对FileInputStream流进行过滤;用DataOuputStream对FileOutputStream流进行过滤,以实现特定数据类型数据的读写。 (2)面向字符的文件访问          以字符文件作为数据源。包括:FileReader类和FileWriter类分别用于字符文件的读、写访问。          基于字符流的数据读写方法与基于字节流的类似,只是将读写的单位由字节改为字符,方法中的字节数组参数相应改为字符数组。例如:  int read(char b[])表示从文件读数据填满数组,返回读到的字符数。          可用BufferedReader对FileReader流进行过滤;用BufferedWriter对FileWriter流进行过滤,其中包含newLine()方法可写入一个换行。 10.2.4  File类 借助File对象,可以获取文件和相关目录的属性信息。其主要方法见表10-2。 表10-2 File类的主要方法 方法 功能 String getName() 返回文件名 String getPath() 返回文件或目录路径 String getAbsolutePath() 返回绝对路径 String getParent() 获取文件所在目录的父目录 boolean exists() 文件是否存在 boolean canWrite() 文件是否可写 boolean canRead() 文件是否可读 boolean isFile() 是否为一个正确定义的文件 boolean isDirectory() 是否为目录 Long lastModified() 文件的最后修改日期 Long length() 文件长度 boolean mkdir() 创建当前目录的子目录 String[] list() 列出目录中的文件 boolean renameTo(File newFile) 将文件改名为新文件名 Void delete() 删除文件 boolean equals(File f) 比较两个文件或目录是否相等 10.2.5  随机文件 创建随机访问文件对象时要指定文件访问的“rw”参数,也就是它可以对同一打开文件进行读写两种访问。RandomAccessFile类实现了DataInput和DataOutput接口,为支持流的随机读写,RandomAccessFile类还添加定义了如下方法:          long getFilePointer():返回当前指针;          void seek(long pos):将文件指针定位到一个绝对地址;          long length():返回文件的长度 注意:地址是相对于文件头的偏移量。地址0表示文件的开头。 10.2.6  对象序列化 (1)对象输入流ObjectInputStream和对象输出流ObjectOutputStream将Java流系统扩充到能输入输出对象,它们提供的writeObject()和readObject()方法实现了对象的串行化(Serialized)和反串行化(Deserialized)。 (2)用对象输入流的readObject()方法必须捕捉ClassNotFoundException异常。 (3)为了实现用户自定义对象的串行化,相应的类必须实现Serializable接口,否则,不能以对象形式正确写入文件。Serializable接口是一个不含任何具体 内容 财务内部控制制度的内容财务内部控制制度的内容人员招聘与配置的内容项目成本控制的内容消防安全演练内容 的接口。 10.3 样例程序 样例1: 编写一个程序实现任意文件的拷贝功能,源文件和目的文件名由命令行参数提供。 【参考程序】 import java.io.*; public class CopyFile {    public static void main(String args[]) {       if ( args.length<2) {         System.out.println("usage: java CopyFile sourcefile targetfile");         System.exit(0);       }       byte[] b = new byte[1024];       try {          FileInputStream infile = new FileInputStream(args[0]);          FileOutputStream targetfile = new FileOutputStream(args[1]);          while (true) {             int byteRead=infile.read(b); //从文件读数据给字节数组             if (byteRead==-1) //在文件尾,无数据可读                 break;  //退出循环                       targetfile.write(b,0,byteRead);  //将读到的数据写入目标文件          }         targetfile.close(); System.out.println("copy success! ");       } catch(IOException e) { }      } } 注:本样例演示面向字节的输入输出流的进行文件读写的方法。 【编程技巧】 (1) 创建一个字节数组存放从文件读取的数据; (2) 利用FileInputStream对象的带字节数组参数的read方法从文件读数据,返回读到的字节数;利用FileOutputStream对象的带字节数组的write方法可将字节数组中指定的字节写入到目标文件。 (3) 利用循环控制文件的连续读写操作,在处理到文件结尾时,read方法返回-1,退出循环。 样例2:编写一个程序统计一个文本文件中字符A的个数,文件名由命令行参数提供。 【参考程序】 import java.io.*; public class readtxt {   static String s;   /*  方法find查找字符串in中A的个数 */   public  static  int find(String in) {     int n=0;     int counter = 0;     while(n!=-1) {        n = in.indexOf((int)'A',n+1);        counter++;          }      return counter-1;    }   public static void main(String[] args) {     try{          int n=0;          FileReader file =new FileReader(args[0]);          BufferedReader in=new BufferedReader (file);          boolean eof=false;          while(!eof)  {             String  x=in.readLine(); //从文件读一行             if(x==null) {  //判是否文件结束                eof=true; }              else                s=s+x;  //将内容拼接到字符串s上         }        System.out.print("the number of A is :"+find(s));         in.close();      }catch(IOException e){ };   } } 注:本样例演示文本文件的数据读取方法。 【编程技巧】 (1) 循环利用BufferedReader的readLine()方法从文件读一行内容,读到文件尾部时将返回null; (2) 将读到的数据拼接到字符串s中,最后执行find方法找出A的个数。   样例3: 设计一个图形界面的文本文件查阅工具,在窗体中安排一个文本域和一个按钮(如图13-1所示),文本域用来显示文件的内容,点击打开按钮将弹出文件选择对话框(如图13-2所示),从而可以选择要查看的文件。   【参考程序】 import java.awt.*; import java.awt.event.*; import java.io.*; public class FileViewer extends Frame implements ActionListener {    String directory; //文件选择对话框的默认目录    TextArea textarea; // 显示文件内容的文本域    public FileViewer() { this(null, null); }    public FileViewer(String filename) { this(null, filename); }    public FileViewer(String directory, String filename) {       addWindowListener(new WindowAdapter() {           public void windowClosing(WindowEvent e) { dispose(); }       });       textarea = new TextArea("", 24, 80);       textarea.setFont(new Font("宋体", Font.PLAIN, 12));       textarea.setEditable(false);       this.add("Center", textarea);       Panel p = new Panel();       p.setLayout(new FlowLayout(FlowLayout.RIGHT, 10, 5));       this.add(p, "South");      Button openfile = new Button("Open File");       openfile.addActionListener(this);       openfile.setActionCommand("open");       openfile.setFont(new Font("SansSerif", Font.BOLD, 14));       p.add(openfile);       this.pack();   // 根据文件名路径得到目录,否则为系统当前目录.        if (directory == null) {           File f;           if ((filename != null) && (f = new File(filename)).isAbsolute()) { //如果文件名中给出了绝对路径,则可根据创建的File对象得到文件的目录路径和文件名               directory = f.getParent();               filename = f.getName();           }           else directory = System.getProperty("user.dir"); //系统当前目录        }       this.directory = directory;    //记住文件打开对话框的默认目录       setFile(directory, filename);  // 装载显示文件    } /* 从特定目录装载文件 */     public void setFile(String directory, String filename) {        if ((filename == null) || (filename.length() == 0)) return;           File f;           FileReader in = null;           try {                f = new File(directory, filename); // 创建文件对象                in = new FileReader(f); // And a char stream to read it                char[] buffer = new char[4096]; // 每次读 4K字符                int len; // 每次读到的字符数                textarea.setText("");                while((len = in.read(buffer)) != -1) {                   String s = new String(buffer, 0, len);                   textarea.append(s); //读到的字符串添加到文本域                }               this.setTitle("FileViewer: " + filename); // 设置窗体标题               textarea.setCaretPosition(0); //将光标定到文本域的开头           }         catch (IOException e) {             textarea.setText(e.getClass().getName() + ": " + e.getMessage());             this.setTitle("FileViewer: " + filename + ": I/O Exception");          } // 任何情况下均要记住关闭流         finally { try { if (in!=null) in.close(); } catch (IOException e) {} }     }     public void actionPerformed(ActionEvent e) {         String cmd = e.getActionCommand();         if (cmd.equals("open")) {            FileDialog f = new FileDialog(this, "Open File", FileDialog.LOAD);            f.setDirectory(directory); //设置文件打开对话框的默认目录            f.show();            directory = f.getDirectory();   // 记住新的默认目录            setFile(directory, f.getFile()); // 装载显示文件            f.dispose(); // 得到文件后自动关闭对话框         }      }    public static void main(String[] args) throws IOException {        Frame f = new FileViewer((args.length == 1)?args[0]:null);        f.addWindowListener(new WindowAdapter() {           public void windowClosed(WindowEvent e) { System.exit(0); }        });        f.setVisible(true);    } } 注:本样例演示File对象的使用以及读取文本文件数据的方法。 【编程技巧】 (1) 如何利用File对象处理文件的目录和文件名,系统的当前目录如何得到; (2) 创建一个字符数组用于存放从文件读到的字符,利用FileReader的read方法可从文件读数据填入字符数组,无数据可读时返回-1,利用它作为循环控制标记; (3)  FileViewer构造方法的多态性编写,从而适应各种应用情形; (4)  FileDialog的使用,文件默认目录路径的设置和获取新默认路径的办法,新默认路径由对话框选择的路径决定。 10.4 上机练习       基本题 1) 编写一个程序将多个文件的内容合并为一个文件,被合并的文件的文件名由命令行参数输入。例如: java merge x1.txt  x2.txt  x3.txt  x4.txt 2)从一个文本文件中读入30个学生的姓名和成绩,计算所有学生的最高分、最低分、平均分,将情况写入另一个文本文件中。 10.5 思考题 1)以下哪个是RandomAccessFile文件的构造方法:  A.RandomAccessFile("data", "r"); B.RandomAccessFile("r", "data"); C.RandomAccessFile("data", "read"); D.RandomAccessFile("read", "data"); 2)设有如下代码: import java.io.*; public class Th{    public static void main(String argv[]){       Th t = new Th();       t.amethod();     }    public void amethod(){       try{         ioCall();       }catch(IOException ioe){}    } } 以下哪个最有可能是ioCall方法的方法体? A. public void ioCall () throws IOException{       DataInputStream din = new DataInputStream(System.in);       din.readChar();     } B. public void ioCall () throw IOException{       DataInputStream din = new DataInputStream(System.in);       din.readChar();    } C. public void ioCall (){       DataInputStream din = new DataInputStream(System.in);       din.readChar();     } D. public void ioCall throws IOException(){           DataInputStream din = new DataInputStream(System.in);       din.readChar();    } 3)当前目录不存在名为Hello.txt的文件,执行下面代码的输出结果为? import java.io.*; public class Mine{    public static void main(String argv[]){        Mine m=new Mine( );        System.out.println(m.amethod());    }    public int amethod(){       try{          FileInputStream file=new FileInputStream("Hello.txt");       }       catch(FileNotFoundException e){           System.out.print("No such file found");           return -1;       }       catch(IOException e){          System.out.print("Doing finally");       }       return 0;    } } A. No such file found B. No such file found-1 C. No such file foundDoing finally-1 D. 0 4) 使用哪个类可创建目录? A. File           B. DataOutput     C. Directory D. FileDescriptor      E.  FileOutputStream 5) 假设raf是一个随机访问文件,以下语句的编译和运行结果为?raf.seek( raf.length() ); A.代码不能编译. B.会出现IOException C.文件指针将定位到文件的最后一个字符之前 D.文件指针将定位到文件的最后一个字符 6)以下哪些是FileOutputStream 构造方法的合法形式? A. FileOutputStream( FileDescriptor fd ) B. FileOutputStream( String n, boolean a ) C. FileOutputStream( boolean a ) D. FileOutputStream() E. FileOutputStream( File f ) 7)以下哪个能编译通过? A.File f = new File("/","autoexec.bat"); B. DataInputStream d = new DataInputStream(System.in); C. OutputStreamWriter o = new OutputStreamWriter(System.out); D. RandomAccessFile r = new RandomAccessFile("OutFile"); 8)以下程序的调试结果为: import java.io.*; class Base{     public void amethod()throws FileNotFoundException{} } public class ExcepDemo extends Base{     public static void main(String argv[]){      ExcepDemo e = new ExcepDemo();     }     public void amethod(){}     protected ExcepDemo(){      try{          DataInputStream din = new DataInputStream(System.in);          System.out.println("Pausing");          din.readByte();          System.out.println("Continuing");          this.amethod();      }catch(IOException ioe) { }     } } A. 由于构造方法为protected导致编译出错 B. 由于amethod方法未声明异常导致编译出错 C. 由于amethod方法未声明异常导致运行错误 D. 输出显示 "Pausing",击键后显示"Continuing"
本文档为【java流式输入输出与文件处理编程】,请使用软件OFFICE或WPS软件打开。作品中的文字与图均可以修改和编辑, 图片更改请在作品中右键图片并更换,文字修改请直接点击文字进行修改,也可以新增和删除文档中的内容。
该文档来自用户分享,如有侵权行为请发邮件ishare@vip.sina.com联系网站客服,我们会及时删除。
[版权声明] 本站所有资料为用户分享产生,若发现您的权利被侵害,请联系客服邮件isharekefu@iask.cn,我们尽快处理。
本作品所展示的图片、画像、字体、音乐的版权可能需版权方额外授权,请谨慎使用。
网站提供的党政主题相关内容(国旗、国徽、党徽..)目的在于配合国家政策宣传,仅限个人学习分享使用,禁止用于任何广告和商用目的。
下载需要: 免费 已有0 人下载
最新资料
资料动态
专题动态
is_748890
暂无简介~
格式:doc
大小:149KB
软件:Word
页数:13
分类:互联网
上传时间:2013-01-18
浏览量:105