如何在java中快捷处理典型文件

    作者:课课家教育更新于: 2016-02-18 17:20:28

    大神带你学编程,欢迎选课

      由于以前采用的一些典型形式都涉及到文件处理,所以大家也许会怀疑为什么要进行那么多的代码输入——这正是装饰器方案一个缺点。本部分将向大家展示如何创建和使用典型文件读取和写入配置的快捷版本。这些快捷版本均置入packagecom.bruceeckel.tools中。为了将每个类都添加到库内,只需将其置入适当的目录,并添加对应的package语句即可。

    如何在java中快捷典型文件处理_java对象_java构建器_课课家

      快速文件输入

      若想创建一个对象,用它从一个缓冲的DataInputStream中读取一个文件,可将这个过程封装到一个名为InFile的类内。如下所示:

      //: InFile.java

      // Shorthand class for opening an input file

      package com.bruceeckel.tools;

      import java.io.*;

      public class InFile extends DataInputStream {

      public InFile(String filename)

      throws FileNotFoundException {

      super(

      new BufferedInputStream(

      new FileInputStream(filename)));

      }

      public InFile(File file)

      throws FileNotFoundException {

      this(file.getPath());

      }

      } ///:~

      无论构建器的String版本还是File版本都包括在内,用于共同创建一个FileInputStream。

      就象这个例子展示的那样,现在可以有效减少创建文件时由于重复强调造成的问题。

      快速输出格式化文件

      亦可用同类型的方法创建一个PrintStream,令其写入一个缓冲文件。下面是对com.bruceeckel.tools的扩展:

      //: PrintFile.java

      // Shorthand class for opening an output file

      // for human-readable output.

      package com.bruceeckel.tools;

      import java.io.*;

      public class PrintFile extends PrintStream {

      public PrintFile(String filename)

      throws IOException {

      super(

      new BufferedOutputStream(

      new FileOutputStream(filename)));

      }

      public PrintFile(File file)

      throws IOException {

      this(file.getPath());

      }

      } ///:~

      注意构建器不可能捕获一个由基础类构建器“掷”出的违例。

      快速输出数据文件

      最后,利用类似的快捷方式可创建一个缓冲输出文件,用它保存数据(与由人观看的数据格式相反):

      //: OutFile.java

      // Shorthand class for opening an output file

      // for data storage.

      package com.bruceeckel.tools;

      import java.io.*;

      public class OutFile extends DataOutputStream {

      public OutFile(String filename)

      throws IOException {

      super(

      new BufferedOutputStream(

      new FileOutputStream(filename)));

      }

      public OutFile(File file)

      throws IOException {

      this(file.getPath());

      }

      } ///:~

      非常奇怪的是(也非常不幸),Java库的设计者居然没想到将这些便利措施直接作为他们的一部分标准提供。

课课家教育

未登录

1