第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.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值