第10章 Java IO 系统
1.输入和输出
输入有关的所有类都从InputStream继承,与输出有关的所有类都从OutputStream继承。
2.增添属性和有用的接口
利用层次化对象动态和透明地添加单个对象的能力的做法叫做“装饰器”方案。
3.本身的缺陷:RandomAccessFile
RandomAccessFile不属于InputStream或者OutputStream分层结构的一部分。只能针对
文件才能操作,不能针对数据流操作。可以在一个文件里向前或向后移动。
4.目录列表器
public interface FilenameFilter {
boolean accept(文件目录, 字串名);
}
通过实现这个接口,可以对文件名进行过滤。下面用的是匿名内部类来实现这个接口。
package exam;
import java.io.*;
public class DirList3 {
public static void main(final String[] args){
try{
File path=new File(".");
String[] list;
if(args.length==-0)
list=path.list();
else
list=path.list(
new FilenameFilter(){
public boolean accept(File dir,String n){
String f=new File(n).getName();
return f.indexOf(args[0])!=-1;
}
}
);
for(int i=0;i<list.length;i++)
System.out.println(list[i]);
}catch(Exception e){
e.printStackTrace();
}
}
}
5.IO流的典型应用
package c10;
import java.io.*;
import oypj.tools.*;
public class IOStreamDemo {
public static void main(String[] args){
try{
//1.Buffered input file
DataInputStream in=new DataInputStream(new BufferedInputStream(new FileInputStream(args[0])));
String s,s2=new String();
while((s=in.readLine())!=null)
s2+=s+"\n";
in.close();
//2.Input from memory
StringBufferInputStream in2=new StringBufferInputStream(s2);
int c;
while((c=in2.read())!=-1)
System.out.print((char)c);
//3.Formatted memory input
try{
DataInputStream in3=new DataInputStream(new StringBufferInputStream(s2));
while(true)
System.out.print((char)in3.readByte());
}catch(EOFException e){
P.rintln("End of stream encountered");
}
//4.Line numbering & file output
try{
LineNumberInputStream li=new LineNumberInputStream(new StringBufferInputStream(s2));
DataInputStream in4=new DataInputStream(li);
PrintStream out1=new PrintStream(new BufferedOutputStream(new FileOutputStream("IOEemo.out")));
while((s=