`

第18章IO系统

 
阅读更多
1.

File类既能代表一个文件,也能代表某个目录下文件和子目录的集合。
java.io
Interface FilenameFilter接口的相关方法
1)accept

boolean accept(File dir,
               String name)

    Tests if a specified file should be included in a file list.

    Parameters:
        dir - the directory in which the file was found.//表示当前对象所代表的目录,是固定的
        name - the name of the file. //表示当前文件名称或子目录名称
    Returns:
        true if and only if the name should be included in the file list; false otherwise.

2)java.io
Interface FileFilter

public interface FileFilter

Method Detail
accept

boolean accept(File pathname)
    Tests whether or not the specified abstract pathname should be included in a pathname list.

    Parameters:
        pathname - The abstract pathname to be tested //代表当前的文件或子目录
    Returns:
        true if and only if pathname should be included



相关例子:
public class DirList {
public static void main(String[] args) {
File path = new File("c:\\");
String[] list;
// if (args.length == 0)
// list = path.list();
// else
list = path.list(new DirFilter("cxm"));
// Arrays.sort(list, String.CASE_INSENSITIVE_ORDER);
for (String dirItem : list)
System.out.println(dirItem);
}
}

class DirFilter implements FilenameFilter {
private Pattern pattern;

public DirFilter(String regex) {
pattern = Pattern.compile(regex);
}

public boolean accept(File dir, String name) {//dir表示当前的目录,name表示当前的文件名称或

子目录名称
System.out.println("================"+name+"================"+dir.toString());
return pattern.matcher(name).matches();
}
}

注意:当调用有参数的list时,该list方法会为目录下的每个文件和子目录调用一次accepte方法,以此来判断该

文件或子目录是否要包含在最终列表中。

也可以用匿名内部类实现,例如:
list = path.list(new FilenameFilter() {
        private Pattern pattern = Pattern.compile(args[0]);
        public boolean accept(File dir, String name) {
          return pattern.matcher(name).matches();
        }
      });

2.file类的相关方法
1)
public String[] list()

    Returns an array of strings naming the files and directories in the directory denoted by this

abstract pathname.

    If this abstract pathname does not denote a directory, then this method returns null. Otherwise

an array of strings is returned, one for each file or directory in the directory. Names denoting

the directory itself and the directory's parent directory are not included in the result. Each

string is a file name rather than a complete path.

    There is no guarantee that the name strings in the resulting array will appear in any specific

order; they are not, in particular, guaranteed to appear in alphabetical order.

    Returns:
        An array of strings naming the files and directories in the directory denoted by this

abstract pathname. The array will be empty if the directory is empty. Returns null if this abstract

pathname does not denote a directory, or if an I/O error occurs.


2)
public String[] list(FilenameFilter filter)

    Returns an array of strings naming the files and directories in the directory denoted by this

abstract pathname that satisfy the specified filter. The behavior of this method is the same as

that of the list() method, except that the strings in the returned array must satisfy the filter.

If the given filter is null then all names are accepted. Otherwise, a name satisfies the filter if

and only if the value true results when the FilenameFilter.accept(java.io.File, java.lang.String)

method of the filter is invoked on this abstract pathname and the name of a file or directory in

the directory that it denotes.

    Parameters:
        filter - A filename filter
    Returns:
        An array of strings naming the files and directories in the directory denoted by this

abstract pathname that were accepted by the given filter. The array will be empty if the directory

is empty or if no names were accepted by the filter. Returns null if this abstract pathname does

not denote a directory, or if an I/O error occurs.

3)

public File[] listFiles()

    Returns an array of abstract pathnames denoting the files in the directory denoted by this

abstract pathname.

    If this abstract pathname does not denote a directory, then this method returns null. Otherwise

an array of File objects is returned, one for each file or directory in the directory. Pathnames

denoting the directory itself and the directory's parent directory are not included in the result.

Each resulting abstract pathname is constructed from this abstract pathname using the File(File,

String) constructor. Therefore if this pathname is absolute then each resulting pathname is

absolute; if this pathname is relative then each resulting pathname will be relative to the same

directory.

    There is no guarantee that the name strings in the resulting array will appear in any specific

order; they are not, in particular, guaranteed to appear in alphabetical order.

    Returns:
        An array of abstract pathnames denoting the files and directories in the directory denoted

by this abstract pathname. The array will be empty if the directory is empty. Returns null if this

abstract pathname does not denote a directory, or if an I/O error occurs.

4)
listFiles

public File[] listFiles(FilenameFilter filter)

    Returns an array of abstract pathnames denoting the files and directories in the directory

denoted by this abstract pathname that satisfy the specified filter. The behavior of this method is

the same as that of the listFiles() method, except that the pathnames in the returned array must

satisfy the filter. If the given filter is null then all pathnames are accepted. Otherwise, a

pathname satisfies the filter if and only if the value true results when the FilenameFilter.accept

(java.io.File, java.lang.String) method of the filter is invoked on this abstract pathname and the

name of a file or directory in the directory that it denotes.

    Parameters:
        filter - A filename filter
    Returns:
        An array of abstract pathnames denoting the files and directories in the directory denoted

by this abstract pathname. The array will be empty if the directory is empty. Returns null if this

abstract pathname does not denote a directory, or if an I/O error occurs.
5)listFiles

public File[] listFiles(FileFilter filter)

    Returns an array of abstract pathnames denoting the files and directories in the directory

denoted by this abstract pathname that satisfy the specified filter. The behavior of this method is

the same as that of the listFiles() method, except that the pathnames in the returned array must

satisfy the filter. If the given filter is null then all pathnames are accepted. Otherwise, a

pathname satisfies the filter if and only if the value true results when the FileFilter.accept

(java.io.File) method of the filter is invoked on the pathname.

    Parameters:
        filter - A file filter
    Returns:
        An array of abstract pathnames denoting the files and directories in the directory denoted

by this abstract pathname. The array will be empty if the directory is empty. Returns null if this

abstract pathname does not denote a directory, or if an I/O error occurs.



3.File类不仅可以代表已存在的目录或文件,还可以创建新的目录和文件


File类的相关方法:
1)renameTo//重新命名目录或文件名

public boolean renameTo(File dest)//dest代表新的名称

    Renames the file denoted by this abstract pathname.

    Many aspects of the behavior of this method are inherently platform-dependent: The rename

operation might not be able to move a file from one filesystem to another, it might not be atomic,

and it might not succeed if a file with the destination abstract pathname already exists. The

return value should always be checked to make sure that the rename operation was successful.

    Parameters:
        dest - The new abstract pathname for the named file
    Returns:
        true if and only if the renaming succeeded; false otherwise
2)exists

public boolean exists()

    Tests whether the file or directory denoted by this abstract pathname exists.

    Returns:
        true if and only if the file or directory denoted by this abstract pathname exists; false

otherwise
3)mkdir

public boolean mkdir()

    Creates the directory named by this abstract pathname.

    Returns:
        true if and only if the directory was created; false otherwise
4)delete

public boolean delete()

    Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a

directory, then the directory must be empty in order to be deleted.

    Returns:
        true if and only if the file or directory is successfully deleted; false otherwise

4.I/O类库通常使用流这个抽象概念,它表示任何有能力产生数据的数据源对象或任何有能力接受数据的接收端对

象。java的I/o类库分为2个部分,一部分是读入Inputstream和Reader;另一部分是OutputStream和Writer。

5.Inputstream表示那些从不同数据源产生输入的类。OutputStream表示输出要去往的目的地。

6.IO流的三种分类方式

   1.按流的方向分为:输入流和输出流

    2.按流的数据单位不同分为:字节流和字符流

    3.按流的功能不同分为:节点流和处理流

流的分类:
  按流向分为输入流和输出流;
  按传输单位分为字节流(Stream)结尾的和字符流(Reader和Writer);
  按功能还可以分为节点流和过滤流。
  节点流:负责数据源和程序之间建立连接;(相当于裸枪)
  过滤流:用于给节点增加功能。(相当于功能零部件)
  过滤流的构造方式是以其他流为参数构造(这样的设计模式称为装饰模式)。
注:I/O流是一类很宝贵的资源,使用完后必须调用close()方法关闭流并释放资源。在关闭流时只用关闭最外层

的流。  

IO流的四大抽象类:

    字符流:Reader Writer

    字节流:InputStream(读数据)OutputStream(写数据)

7.字节流的字符编码:
  字符编码把字符转换成数字存储到计算机中,按ASCii 将字母映射为整数。
  把数字从计算机转换成相应的字符的过程称为解码。
  乱码的根源在于编解码方式不统一。在世界上任何一种编码方式中都会向上兼容ASCII码。所以英文没有乱码。
  编码方式的分类:
  ASCII(数字、英文):1 个字符占一个字节(所有的编码集都兼容ASCII)
  ISO8859-1(欧洲):1 个字符占一个字节
  GB-2312/GBK:1 个字符占两个字节。GB代表国家标准。
  GBK是在GB-2312上增加的一类新的编码方式,也是现在最常用的汉字编码方式。
  Unicode: 1 个字符占两个字节(网络传输速度慢)
  UTF-8:变长字节,对于英文一个字节,汉字三个字节。
  原则:保证编解码方式的统一,才能不至于出现错误。 
  I/O学习种常范的两个错误 1。忘了加flush2.没有加换行。

8.java I/O类库需要多种不同功能的组合,这正是使用装饰器模式的理由所在。装饰器模式也有缺点:在带来灵

活性的同时也增加了代码的复杂性。java IO类库操作不便的原因就在于:我们必须创建许多类(核心类上添加许

多装饰器),才能得到我们想要的IO对象。FilterInputStream和FilterOutputStream是所有装饰器类的2个基类



9.java1.1对基本的流库进行了重大修改,添加了Reader和Writer,这2个类主要是为了国际化,支持unicode。而

之前的InputStream和outputStream只支持8位的字节流,而且新类的设计使得它的操作比旧类库更快。有时候需

要在这两个类型之间转换,需要用到适配器。InputStreamReader可以把InputSteam转换为

Reader,OutputSreamWriter可以把outputSream转换为Writer。

10.IO典型的使用方式之一:
public class BufferedInputFile {
  // Throw exceptions to console:
  public static String
  read(String filename) throws IOException {
    // Reading input by lines:
    BufferedReader in = new BufferedReader(
      new FileReader(filename));
    String s;
    StringBuilder sb = new StringBuilder();
    while((s = in.readLine())!= null)
      sb.append(s + "\n");
    in.close();
    return sb.toString();
  }
  public static void main(String[] args)
  throws IOException {
    System.out.print(read("BufferedInputFile.java"));
  }
} /* (Execute to see output) *///:~
为了提高速度,这里使用了缓存。相关类说明如下:
1)
java.lang.Object
  extended by java.io.Reader
      extended by java.io.InputStreamReader
          extended by java.io.FileReader

public class FileReader
extends InputStreamReader
Constructor Summary
FileReader(File file)
          Creates a new FileReader, given the File to read from.
FileReader(FileDescriptor fd)
          Creates a new FileReader, given the FileDescriptor to read from.
FileReader(String fileName)
          Creates a new FileReader, given the name of the file to read from.
该类没有方法,都是从基类继承而来的。

2)
java.lang.Object
  extended by java.io.Reader
      extended by java.io.BufferedReader

public class BufferedReader
extends Reader

Read text from a character-input stream, buffering characters so as to provide for the efficient

reading of characters, arrays, and lines.

The buffer size may be specified, or the default size may be used. The default is large enough for

most purposes.

In general, each read request made of a Reader causes a corresponding read request to be made of

the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around

any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders. For

example,

BufferedReader in
   = new BufferedReader(new FileReader("foo.in"));


will buffer the input from the specified file. Without buffering, each invocation of read() or

readLine() could cause bytes to be read from the file, converted into characters, and then

returned, which can be very inefficient.

Programs that use DataInputStreams for textual input can be localized by replacing each

DataInputStream with an appropriate BufferedReader.
构造函数
Constructor Summary
BufferedReader(Reader in)
          Create a buffering character-input stream that uses a default-sized input buffer.
BufferedReader(Reader in, int sz)
          Create a buffering character-input stream that uses an input buffer of the specified

size.
相关的主要方法
readLine

public String readLine()
                throws IOException

    Read a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a

carriage return ('\r'), or a carriage return followed immediately by a linefeed.

    Returns:
        A String containing the contents of the line, not including any line-termination

characters, or null if the end of the stream has been reached

10.流的来源或目的地并不一定是文件,也可以是内存中的一块空间,例如一个字节数组。流的来源或目的地并不一定是文件,也可以是内存中的一块空间,例如一个字节数组。

11.new PrintWriter(new File()) 自动就用了缓存,不必须在用缓存装饰器类包装,但是其他类没有这个功能。

12.该类提供了把数据编码成多种不同类型的字符集的工具
java.lang.Object
  extended by java.nio.charset.Charset

All Implemented Interfaces:
    Comparable<Charset>

public abstract class Charset
extends Object
implements Comparable<Charset>

A named mapping between sequences of sixteen-bit Unicode code units and sequences of bytes. This class defines methods for creating decoders and encoders and for retrieving the various names associated with a charset. Instances of this class are immutable.

This class also defines static methods for testing whether a particular charset is supported, for locating charset instances by name, and for constructing a map that contains every charset for which support is available in the current Java virtual machine. Support for new charsets can be added via the service-provider interface defined in the CharsetProvider class.

All of the methods defined in this class are safe for use by multiple concurrent threads.
分享到:
评论

相关推荐

    nxp lpc11c14中文手册

    第一章 概述 第二章 存储器映射 第三章 系统配置 ...第十八章 系统节拍定时器 第十九章 模数转换器(ADC) 第二十章 Flash存储器编程固件 第二十一章 串行线调试(SWD) 第二十二章 ARM Cortex-M0参考资料

    msp430单片机通用userguide中文资料

    第一章:430单片机体系...第八章:TimerA 第九章:TimerB 第十章:USI通信模块 第十一章:UART通信 第十二章:SPI通信 第十三章:IIC通信 第十四章:OA放大器 第十五章:比较器 第十六章:ADC 第十七章:16为模数转换

    操作系统精髓与设计原理课后答案(中文版)

    第11章_IO管理和磁盘调度讨论了输入/输出操作对系统性能的影响。磁盘调度算法(如FCFS、SCAN、C-SCAN、LOOK等)用于优化磁头移动,提高数据读写的效率。 最后,第16章_安全涉及操作系统中的安全问题,包括权限控制...

    跟我学JAVA

    图文并茂适合初学者 第1章 Java概述.ppt 第2章 Java开发环境.ppt 第3章 Java语言基础.ppt 第4章 程序流程控制.ppt 第5章 字符串.ppt 第6章 数组.ppt 第7章 对象与类.ppt ...第18章 KTV管理系统.ppt

    VisualC++实例精通光盘代码

    第1章 认识Visua0 C++6.0 第2章 使用常用W8n32控件 第3章 使用高级W5n32控件丰富界面 第4章 窗体 第5章 对话框 第6章 深入了解Windows消息 第7章 系统和外壳编程 第8章 基本输入设备 ...第18章 发布应用程序

    疯狂android讲义源代码.7z.001(共三卷)

    第一章android应用与开发环境 第二章android应用的界面编程 第三章事件处理 第四章深入理解activity 第五章使用intent和intentFilter进行通信 第六章android应用的资源 ...第十八章疯狂连连看 第十九章电子拍卖系统

    疯狂android讲义源代码.7z.003(共三卷)

    第一章android应用与开发环境 第二章android应用的界面编程 第三章事件处理 第四章深入理解activity 第五章使用intent和intentFilter进行通信 第六章android应用的资源 ...第十八章疯狂连连看 第十九章电子拍卖系统

    疯狂android讲义源代码.7z.002(共三卷)

    第一章android应用与开发环境 第二章android应用的界面编程 第三章事件处理 第四章深入理解activity 第五章使用intent和intentFilter进行通信 第六章android应用的资源 ...第十八章疯狂连连看 第十九章电子拍卖系统

    我用V isio 制图

    第五至第八章通过一系列综合实例进一步深化了读者的理解,这些实例覆盖了Visio2003在绘制多种类型图形中的应用,如流程图、网络图、组织结构图等。每一章节都精选了具体案例,详细展示了如何从零开始构建一个完整的...

    GE PLC Genius IO离散量和模拟量模块用户手册

    第十八章【I/O模块故障查找】则提供了模块LED指示灯状态的解释,并给出了排除故障的步骤和方法。这部分内容对于现场维护人员来说十分关键,能够帮助他们快速诊断并解决问题,从而缩短系统的停机时间。 最后,附录A...

    ASP.NET 3.5 从基础到项目实战

    ASP.NET 3.5 从基础到项目实战 第1章 .ASP.NET入门 第2章 C#语言基础 第3章 System.IO命名空间 第4章 ASP.NET Web服务器控件 第5章 网站设计 第6章 ASP.NET数据库编程 第7章 网络安全与验证 ...第18章 ASP.NET Shoping

    物联网嵌入式培训视频.zip

    网盘文件永久链接 01_第一章_介绍 02_第二章_uboot 03_第三章_kernel 04_第四章_rootfs 05_第五章_内核模块 06_第六章_chrdev 07_第七章_字符设备驱动接口 08_第八章_GpioSubSystem_interrupt ...13_第十三章_I2C子系统

    Java开发详解.zip

    031807_【第18章:图形界面】_不弹起的按钮组件:JToggleButton笔记.pdf 031808_【第18章:图形界面】_文本组件:JTextComponent笔记.pdf 031809_【第18章:图形界面】_事件处理笔记.pdf 031810_【第18章:图形界面...

    华清远见驱动教程

    -第1章、设备驱动概述 -第2章、驱动设计的硬件基础 ...-第18章、LCD设备驱动 -第19章、Flash设备驱动 -第20章、USB主机与设备驱动 -第21章、PCI设备驱动 -第22章、Linux设备驱动的调试 -第23章、Linux设备驱动的移植

    左万历 操作系统教程 第三版 课件

    7. **第八章 设备与IO管理**:讲解输入/输出设备的工作原理,I/O控制方式(如程序控制、中断驱动、DMA),以及设备调度策略,如公平性和效率的权衡。 8. **第九章 网络与分布式操作系统**:这部分可能涵盖网络基础...

    JMeter高级性能测试实战教程

    分享一套JMeter高级视频教程——《JMeter高级性能测试实战》,课程一共30章,...第18章操作系统层面的分析--对CPU/内存/网络/IO要怎么分析 第19章压力和cpu/内存/网络/io使用率及软中断和上下文切换关系 第20章如何对文

    疯狂Android讲义源码

    目录: 第2章、Android应用程序界面设计,即View 第3章、Android事件处理,包括按键响应机制和消息传递机制 第4章、深入理解Activity ...第18章、疯狂连连看 第19章、电子拍卖系统 里面有很多例子,适合学习。

    疯狂Android讲义(第2版)完整清晰版.part2

    疯狂Android讲义第二版 李刚著 电子工业出版社 2013年3月第1版 【分三个压缩包,需把三个压缩包下载完】 疯狂Android讲义(第2版)完整清晰版.part1.rar ...第18章 疯狂连连看 第19章 电子拍卖系统

    Android第十八章Android架构模式

    "Android第十八章Android架构模式"可能涵盖了一系列用于优化Android应用程序设计的模式。这些模式旨在提高代码的可读性、测试性和可复用性,从而降低长期维护成本。在本章节中,我们可能会学习到以下几种常见的...

Global site tag (gtag.js) - Google Analytics